BeautySandra
BeautySandra

Reputation: 81

HashMap return the lasted record if it has multiple records with the same key, but different value

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

Answers (1)

tarabor
tarabor

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

Related Questions