0

Using this structure: Map<Set, Set> I make a two way relationship:

Set A -> Set B Set B -> Set A

When I obtain Set B using set A, add an Integer to Set B, it no longer returns me Set A from the map, it returns null. Since it should be the same object even after adding an Integer, why does this break the relationship?

Recreated here:

Map<Integer, Set<Integer>> map = new HashMap<>();
Map<Set<Integer>, Set<Integer>> pairs = new HashMap<>();
Set<Integer> a = new HashSet<>();
a.add(1);
map.put(1, a);
Set<Integer> b = new HashSet<>();
b.add(2);
map.put(2, b);
pairs.put(a, b);
pairs.put(b, a);

Later I try to access set b using set a, calling it "opposite". As soon as I add an Integer to opposite, it breaks the relationship. Accessing the map using opposite beforehand gets the original pair, a. But after adding an Integer to opposite, it no longer returns a from the map.

Set<Integer> opposite = pairs.get(a);
System.out.println("get BEFORE adding Integer to set" + pairs.get(opposite));
//pairs.get(orig):[1] <-- returned set has 1
opposite.add(3);
System.out.println("get AFTER adding Integer to set" + pairs.get(opposite));
//pairs.get(orig):null <- can no longer find the set

Yet when I print the "pairs" map, everything looks in tact, so why is it return null?

System.out.println("pairs: " + pairs);
//pairs: {[1]=[2, 3], [2, 3]=[1]}
Mugunga
  • 45
  • 4

0 Answers0