Reputation: 1
The internal implementation of HashSet .......................................
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
{
private transient HashMap<E,Object> map;
private static final Object PRESENT = new Object();
//constructors
public HashSet() {
map = new HashMap<>();
}
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}
public HashSet(Collection<? usnoextends E> c) {
map = new HashMap<>(Math.imax((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
//add method
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
}
Internally HashSet is using HashMap only and performance-wise HashMap is faster than HashSet So why we are not using HashMap directly instead of going for HashSet.
Upvotes: 0
Views: 217
Reputation: 2360
As pointed by @m.antkowicz, though it internally uses HashMap, there is no guarantee.
Another major reason:
Set
(or Collection
)Set
(or Collection
)Also, different implementations of Set
use different Map
ConcurrentSkipListSet
uses ConcurrentNavigableMap
HashSet
uses HashMap
So, this is difficult to use exactly in interface contracts.
Upvotes: 0
Reputation: 13571
Because HashSet
is another type of collection - focused on the single object rather than pair of items. To make HashMap
work like HashSet
we would need to provide everywhere some artificial value
object like
HashMap<MyItem, Object> set;
and then instead of e.g. set.add(new MyItem())
use something like set.put(new MyItem(), null)
what makes no sense and can cause serious issues (when type of Object
will be changed, when you will need to serialize etc)
Moreover internal implementation is nothing you should take care of - it can change in the next Java version (probably won't) and some another mechanism will be used underneath. The most important is Set
interface and the fact HashSet
is implementing this
What is the difference between Lists, ArrayLists, Maps, Hashmaps, Collections etc..?
Upvotes: 3