Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Using HashMap with List<> as Key

I'm trying to use HashMap and Hastable with a List of Object as Key. Please see below a simplified version of my code which doesn't work. When I debug this code, I expect having 3 items in the TestMap4 Object but there is only 1.

List<String> lst = new ArrayList<>();
lst.add("Hello");
lst.add("World");

Map<List<String>, Integer> testMap4 = new HashMap<List<String>, Integer>();
testMap4.put(lst, 1);
testMap4.put(lst, 2);
testMap4.put(lst, 5);

What happens when I put a new item into the HashMap object ? why doesn't it work ?

I obtain the same result with this new example below. (Each List countains the same 2 String)

List<String> lst = new ArrayList<>();
lst.add("Hello");
lst.add("World");

List<String> lst2 = new ArrayList<>();
lst2.add("Hello");
lst2.add("World");

List<String> lst3 = new ArrayList<>();
lst3.add("Hello");
lst3.add("World");

Map<List<String>, Integer> testMap4 = new HashMap<List<String>, Integer>();
testMap4.put(lst,1);
testMap4.put(lst2,2);
testMap4.put(lst3,5);

If I modify only 1 char of the 2 String, this is OK

like image 443
ManWithNoName Avatar asked Mar 08 '26 23:03

ManWithNoName


1 Answers

You do not understand the concept of HashMap.

Your problem is that you are using the same key each time.

testMap4.put(lst, 1);     // <----same key, different value
testMap4.put(lst, 2);     // <----same key, different value
testMap4.put(lst, 5);     // <----same key, different value

In Hashmap, every value that is stored in the Hashmap, there's a key that is saved with that particular value and is unique for each value stored in Hashmap

Important points about HashMap:

1- A HashMap contains values based on the key.

2- It contains only unique elements.

3- It may have one null key and multiple null values.

4- It maintains no order.

Example

 HashMap<Integer,String> hm = new HashMap<>();  

Secondarily, using a mutable object (a List<>) as the key results in undefined behavior if any of the lists are modified after they are inserted into the map. The hash code is calculated according to the contract for List (see the Javadoc) only when the entry is first inserted into the map. A change to the list's contents will change the hash code and you will no longer be able to find the entry.

Using a List<> (or any mutable object) as the key in a HashMap<> is a Really Bad Idea™.

like image 86
Yousaf Avatar answered Mar 11 '26 12:03

Yousaf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!