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]
In the
Map
interface, each key is also unique (java docs):This means, the
HashMap
is already taking care of avoiding duplicate keys, which are the elements of theHashSet