Reputation: 83
I have a Map object where I use integers as the keys, and Lists as the corresponding values. Here is my code.
Map<Integer, List<Double>> dataDouble = new HashMap<Integer, List<Double>>();
List<Double> dubList = new ArrayList<Double>();
for(double i = 0; i < 10; i++)
dubList.add(i);
dataDouble.put(1, dubList);
//dubList.clear();
for(int i = 10; i < 16; i++)
dubList.add(i);
dataDouble.put(2, dubList);
Set<Integer> keyset = dataDouble.keySet();
for(Integer key : keyset) {
System.out.println("\t\tKEY: " + key);
List<Double> finList = dataDouble.get(key);
for(double value : finList)
System.out.println("VALUE: " + value);
}
}
If I do not include the clear statement then the second list is not updated, and I get 2 block of 1 to 10 in the print statements. If I do add the clear command, only 10-15 is printed in the two blocks.
My question is, why does the clear command clear data already added to the Map, and also why does adding new data to the list and putting it on the Map not actually change the values?
Edit: I know I am using double instead of int, in my actual project I am dealing with double values
Upvotes: 1
Views: 3199
Reputation: 930
You are using a reference to the same ArrayList
named dubList, and adding that reference to your map twice. You need to have two seperate ArrayList
declarations.
Map<Integer, List<Double>> dataDouble = new HashMap<Integer, List<Double>>();
List<Double> dubList = new ArrayList<Double>();
for(double i = 0; i < 10; i++)
dubList.add(i);
dataDouble.put(1, dubList);
//add a new ArrayList
List<Double> dubList2 = new ArrayList<Double>();
for(int i = 10; i < 16; i++)
dubList2.add(i);
dataDouble.put(2, dubList2);
Set<Integer> keyset = dataDouble.keySet();
for(Integer key : keyset) {
System.out.println("\t\tKEY: " + key);
List<Double> finList = dataDouble.get(key);
for(double value : finList)
System.out.println("VALUE: " + value);
}
}
Upvotes: 1
Reputation: 10613
You aren't putting a different ArrayList
under the different keys in the HashMap
. You're putting the same ArrayList
under each one. That means that any change that gets made to it will be reflected in all of them (since they're all the same object).
If you want to have multiple different List
s, you need to create a new one with new ArrayList<>()
. So replace the line where you clear
it with dubList = new ArrayList<>()
, and it will correctly give you a new instance.
Upvotes: 3
Reputation: 21975
You're using the same object for all the entries you're adding to the map.
After having added it, change the List
the reference is pointing to.
dataDouble.put(1, dubList);
dubList = new ArrayList<>(); <--- HERE
for(int i = 10; i < 16; i++)
dubList.add(i);
Upvotes: 2