fork(1) download
  1. import java.util.*;
  2.  
  3. class Example {
  4. public static void main(String[] args) {
  5. Set<String> identityA = newIdentityHashSet();
  6. Set<String> identityB = newIdentityHashSet();
  7.  
  8. identityA.add("X");
  9. identityB.add(new String("X"));
  10.  
  11. System.out.println("This should be [X, X]:");
  12. System.out.println(" " + unionInHashSet(identityA, identityB));
  13.  
  14. System.out.println("Returning an identity hash set solves this:");
  15. System.out.println(" " + unionInIdentityHashSet(identityA, identityB));
  16.  
  17. Set<String> a = new HashSet<>(identityA);
  18. Set<String> b = new HashSet<>(identityB);
  19.  
  20. System.out.println("But now the union of regular sets is messed up:");
  21. System.out.println(" " + unionInIdentityHashSet(a, b));
  22. }
  23.  
  24. static <T> Set<T> unionInHashSet(Set<T> a, Set<T> b) {
  25. Set<T> union = new HashSet<>();
  26. union.addAll(a);
  27. union.addAll(b);
  28. return union;
  29. }
  30.  
  31. static <T> Set<T> unionInIdentityHashSet(Set<T> a, Set<T> b) {
  32. Set<T> union = newIdentityHashSet();
  33. union.addAll(a);
  34. union.addAll(b);
  35. return union;
  36. }
  37.  
  38. static <T> Set<T> newIdentityHashSet() {
  39. return Collections.newSetFromMap(new IdentityHashMap<>());
  40. }
  41. }
Success #stdin #stdout 0.04s 2184192KB
stdin
Standard input is empty
stdout
This should be [X, X]:
    [X]
Returning an identity hash set solves this:
    [X, X]
But now the union of regular sets is messed up:
    [X, X]