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?
You need to check put method in Hash map first as HashSet is backed up by HashMap
In the case of
HashMap
, it replaces the old value with the new one.In the case of
HashSet
, the item isn't inserted.The docs are pretty clear on this:
HashSet.add
doesn't replace:But
HashMap.put
will replace:It the case of HashSet, it does NOT replace it.
From the docs:
http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html#add(E)
"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."
HashMap
basically containsEntry
which subsequently containsKey(Object)
andValue(Object)
.InternallyHashSet
areHashMap
andHashMap
do replace values as some of you already pointed..but does it really replaces the keys???No ..and that is the trick here.HashMap
keeps its value as key in the underlyingHashMap
and value is just a dummy object.So if u try to reinsert same Value in HashMap(Key in underlying Map).It just replaces the dummy value and not the Key(Value for HashSet).Look at the below code for HashSet Class:
Here e is the value for HashSet but key for underlying map.and key is never replaced. Hope i am able to clear the confusion.
Correct me if I'm wrong but what you're getting at is that with strings, "Hi" == "Hi" doesn't always come out true (because they're not necessarily the same object).
The reason you're getting an answer of 1 though is because the JVM will reuse strings objects where possible. In this case the JVM is reusing the string object, and thus overwriting the item in the Hashmap/Hashset.
But you aren't guaranteed this behavior (because it could be a different string object that has the same value "Hi"). The behavior you see is just because of the JVM's optimization.