Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have a HashMap with unique keys in java?

Tags:

java

hashmap

How can I have a HashMap with unique keys in Java? Or even does this make any sense to have unique keys in HashMap or the keys are unique by default? I am a newbie. thx

like image 816
Hossein Avatar asked Jan 19 '12 08:01

Hossein


People also ask

Does HashMap contain unique element?

A HashMap contains values based on the key. It contains only unique elements.

Which of these methods does a Java HashMap use to make sure data items are unique?

Key notes on internal working of HashMap Key object's hashCode() is required to calculate the index location of Entry object. Key object's equals() method is used to maintain uniqueness of keys in map.

Why HashMap does not allow duplicate keys?

HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.


2 Answers

Hash map key is unique. Add duplicate key, then it will be overwritten.

 HashMap hm = new HashMap();  hm.put("1", new Integer(1));  hm.put("2", new Integer(2));  hm.put("3", new Integer(3));  hm.put("4", new Integer(4));  hm.put("1", new Integer(5));// value integer 1 is overwritten by 5 

By default Hashmap is not synchronized.

like image 95
Kushan Avatar answered Sep 28 '22 00:09

Kushan


The keys are unique in all maps. The difference between the various maps implementations concern the possibility of null keys, the order of iteration and concurrency issues.

like image 28
xpapad Avatar answered Sep 27 '22 22:09

xpapad