1
Map<Integer, Configuration> m

Configuration {
    int configNumber;
    Map<Integer, Pair<Set<Address>, Set<Integer>>> groupInfo;
}

My map m essentially maps the configNumber to Configuration class. Future configNumber requires information from previous configNumber's values. However, when I add a new configNumber into my map, the second Set<Integer>> follows with the Set<Integer>> of the newly put configNumber. For example:

Initial:

  • Key: 0, Value: Configuration(configNum=0, groupInfo={1=([server3, server2, server1],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10])})

When I add a new Key, say 1:

  • Key: 0, Value: Configuration(configNum=0, groupInfo={1=([server3, server2, server1],[6, 7, 8, 9, 10])})

  • Key: 1, Value: Configuration(configNum=1, groupInfo={1=([server3, server2, server1],[6, 7, 8, 9, 10]), 2=([server6, server5, server4],[1, 2, 3, 4, 5])})

As you can see, key 0's right Set<Integer> in the pair changes with what was recently put. I thought that this was a problem of reference. But every time I created a new HashMap<>() and put all the values there before accessing it. Any tips would be appreciated.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
Rking14
  • 325
  • 2
  • 5
  • 17

1 Answers1

0

The most obvious cause would be re-using the Set<Integer> or the Pair<> from the first entry when constructing the second one. But without your code, we can't tell.

This is one reason I advocate for copy-on-write in public APIs; if someone you don't know is providing you with a collection, make your own copy before storing it. (If you ever start getting ConcurrentModificationExceptions you know you need to start doing this.)

DavidW
  • 1,413
  • 10
  • 17