48

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

Hossein
  • 40,161
  • 57
  • 141
  • 175
  • 5
    Keys _are_ unique by default. Note that `.keySet()` on a `Map` returns a `Set`, and elements of a `Set` are unique by default. If you attempt to push a value to an existing key, the old value will be overwritten. – fge Jan 19 '12 at 08:54
  • 1
    note that "unique" in java means equal in terms of implementation of the methods equals and hashcode! – Hachi Jan 19 '12 at 09:04

6 Answers6

61

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.

Gaur93
  • 685
  • 7
  • 19
Kushan
  • 10,657
  • 4
  • 37
  • 41
  • so how do we make the key value relationship not unique,i.e,i want also the value 5 for the key 1 above ?Is there any method to serve that purpose – Vamsi Pavan Mahesh Dec 21 '13 at 04:51
  • @VamsiPavanMahesh, you will have to store some sort of `List` or `Map` for that corresponding `key`. `Map m = new HashMap<>();` – Emz Nov 22 '15 at 19:34
41

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.

xpapad
  • 4,376
  • 1
  • 24
  • 25
2

Try to look at the Java API for Map which is interface that HashMap implements. The first sentence is:

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

PrimosK
  • 13,848
  • 10
  • 60
  • 78
1

HasMap has unique keys. as .keySet() returns Set which has unique members

Anish Mohile
  • 183
  • 1
  • 1
  • 10
1

HashMap is a collection to store (key,value) pairs and According to the documentation of HashMap the keys are always unique.

If you add a key which already exists(collision) in the hashmap, the old value will be replaced.

Rajesh Pantula
  • 10,061
  • 9
  • 43
  • 52
1

A generic hashmap is usually implemented as an associative array, so let's say your array has N elements, from 0 to N-1, when you want to add a new (key, value) pair, what it's done behind the scenes is (just conceptually):

  1. index = hash(key) mod N
  2. array[index] = value

So, by construction, a key is mapped to one and one only array entry.

Please note that it's actually a bit more complex than this: I am ignoring on purpose things like collision handling, rehashing, etc, you may have a good general idea here https://en.wikipedia.org/wiki/Hash_table

Savino Sguera
  • 3,522
  • 21
  • 20