Reputation: 481
HashSet internally calling HashMap to avoid duplicates in the implementation
public HashSet() {
map = new HashMap<E,Object>();
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
For Example
Code:
Set hashSet = new HashSet();
hashSet.add("Abraham");
hashSet.add("Billy");
hashSet.add("Billy");
System.out.println("HashSet Value " +hashSet.toString());
Output:
HashSet Value [Billy, Abraham]
Upvotes: 0
Views: 850
Reputation: 178441
In the Map
interface, each key is also unique (java docs):
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
This means, the HashMap
is already taking care of avoiding duplicate keys, which are the elements of the HashSet
Upvotes: 1