Does adding a duplicate value to a HashSet/HashMap replace the previous value
Please consider the below piece of code:
HashSet hs = new HashSet();
hs.add("hi"); -- (1)
hs.add("hi"); -- (2)
hs.size()
will give 1 as HashSet
doesn't allow duplicates so only one element will be stored.
I want to know if we add the duplicate element, then does it replace the previous element or it simply doesn't add it?
Also, what will happen usingHashMap
for the same case?
Solution 1:
In the case of HashMap
, it replaces the old value with the new one.
In the case of HashSet
, the item isn't inserted.
Solution 2:
The first thing you need to know is that HashSet
acts like a Set
, which means you add your object directly to the HashSet
and it cannot contain duplicates. You just add your value directly in HashSet
.
However, HashMap
is a Map
type. That means every time you add an entry, you add a key-value pair.
In HashMap
you can have duplicate values, but not duplicate keys. In HashMap
the new entry will replace the old one. The most recent entry will be in the HashMap
.
Understanding Link between HashMap and HashSet:
Remember, HashMap
can not have duplicate keys. Behind the scene HashSet
uses a HashMap
.
When you attempt to add any object into a HashSet
, this entry is actually stored as a key in the HashMap
- the same HashMap
that is used behind the scene of HashSet
. Since this underlying HashMap
needs a key-value pair, a dummy value is generated for us.
Now when you try to insert another duplicate object into the same HashSet
, it will again attempt to be insert it as a key in the HashMap
lying underneath. However, HashMap
does not support duplicates. Hence, HashSet
will still result in having only one value of that type. As a side note, for every duplicate key, since the value generated for our entry in HashSet is some random/dummy value, the key is not replaced at all. it will be ignored as removing the key and adding back the same key (the dummy value is the same) would not make any sense at all.
Summary:
HashMap
allows duplicate values
, but not keys
.
HashSet
cannot contains duplicates.
To play with whether the addition of an object is successfully completed or not, you can check the boolean
value returned when you call .add()
and see if it returns true
or false
. If it returned true
, it was inserted.
Solution 3:
The docs are pretty clear on this: HashSet.add
doesn't replace:
Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.
But HashMap.put
will replace:
If the map previously contained a mapping for the key, the old value is replaced.