Reputation: 81
I have the following map..
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(1,"tom");
hmap.put(1,"jerry");
hmap.put(1,"Jeff");
System.out.println(hmap.get(1));
The output is "Jeff"
Why it always returns the latest record?
Upvotes: 0
Views: 16
Reputation: 166
An HashMap, store items in "key/value" pairs. The key is unique inside a Map. So when you are doing a put on an existing key, you are overwriting the value, you lost the previous one. Thus, always the latest inserted record is returned.
You can check this link https://www.w3schools.com/java/java_hashmap.asp or the official doc at https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
Upvotes: 1