简体   繁体   中英

About Java HashMap: when key is a Set<Integer>

I have a toCopy HashMap that's of the form HashMap<String, Set<Integer>> . The key of toCopy is a string consists of two numbers, like "01" or "10".

When I want to add a value to the entry "01", I did

toCopy.get("01").add(1);

In this case, for some reason both "01" and "10" entries' values were updated. Can someone help me figure out why this happened?

I also tried doing:

Set<Integer> a = toCopy.get("01")
a.add(1)
toCopy.put("01",a)

But the outcome is the same.

I tried using debugger to find out what's going on, but it seems that the hashmap just updated two entries at the same time..

Edit: here is my code

    Map<String,Set<Integer>> toCopy = new HashMap<>();
    // initialize toCopy map
    for(int d1 = 0; d1<dataCenters;d1++){
        for(int d2 = 0; d2<dataCenters;d2++){
            if(d1!=d2){
                Set<Integer> value = new HashSet<>();

                String key1 = Integer.toString(d1).concat(Integer.toString(d2));
                String key2 = Integer.toString(d2).concat(Integer.toString(d1));


                toCopy.put(key1,value);
                toCopy.put(key2,value);
            }
        }
    }
    System.out.println(toCopy);

    for(int i = 0; i < dataCenters; i++){
        for(int j = 1; j < dataCenters-1; j++){
            // data from two centers
            Set<Integer> d1Data = data.get(i);
            Set<Integer> d2Data = data.get(j);
            // d1 => d2
            // loop over data in d1, find those needed to be transferred
            for(Integer d1: d1Data) {
                String d1Tod2 = Integer.toString(i).concat(Integer.toString(j));
                if(!d2Data.contains(d1)){

                    toCopy.get("01").add(d1);
                }
            }

You are putting the same value Set for two different keys :

        Set<Integer> value = new HashSet<>();

        String key1 = Integer.toString(d1).concat(Integer.toString(d2));
        String key2 = Integer.toString(d2).concat(Integer.toString(d1));


        toCopy.put(key1,value);
        toCopy.put(key2,value); 

That's why changing one of them changes both.

You need to create a different Set for each key :

        Set<Integer> value1 = new HashSet<>();
        String key1 = Integer.toString(d1).concat(Integer.toString(d2));
        toCopy.put(key1,value1);
        Set<Integer> value2 = new HashSet<>();
        String key2 = Integer.toString(d2).concat(Integer.toString(d1));
        toCopy.put(key2,value2); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM