Here is what I tried:
HashMap<String, List<Integer>> hmap = new HashMap<String, List<Integer>>();
List<Integer> valueList = new ArrayList<Integer>();
valueList.add(9);
valueList.add(8);
valueList.add(7);
valueList.add(6);
hmap.put("A", valueList);
valueList.add(5);
valueList.add(4);
valueList.add(3);
valueList.add(2);
hmap.put("B", valueList);
valueList.add(7);
valueList.add(6);
valueList.add(5);
valueList.add(4);
hmap.put("C", valueList);
valueList.add(2);
valueList.add(3);
valueList.add(4);
valueList.add(5);
hmap.put("D", valueList);
When I try to retrieve the values of a specific key from hmap
by doing this:
List<Integer> dimensions = hmap.get("A")
I am expecting the hash map to return [9,8,7,6]
but instead it returns everything in the ArrayList i.e., [9,8,7,6,5,4,3,2,7,6,5,4,2,3,4,5]
. How do I make the array list to push only the first values to that key in the HashMap
? What am I missing?
I also tried valueList.clear()
after each hmap.put() statement
. That results in pushing only the last set of values i.e., [2,3,4,5]
for all the keys in the HashMap
.
It happens because you use the same valueList
over again and again which continuously updates the values.
Put to each map entry a new separated list.
// ...
valueList.add(6);
hmap.put("A", valueList);
valueList = new ArrayList<Integer>();
valueList.add(5);
// ...
valueList.add(2);
hmap.put("B", valueList);
valueList = new ArrayList<Integer>();
valueList.add(7);
// ... etc
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments