is HashSet is implemented via a HashMap instance
I am wondering since the HashSet is implemented via a HashMap instance , what would be the key that would be used to put data into HashSet.
i gone through the link 开发者_运维百科http://www.coderanch.com/t/251832/Programmer-Certification-SCJP/certification/Difference-HashMap-HashSet...
which i dint understood properly.. Can anybody help me to understand it better
From the source:
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
the key would be the object that went into the hashset itself since keys of maps are sets.
The idea is to use the object you add to the HashSet
as a key of the HashMap
. That way the add
, remove
, and contains
run in O(1).
Yes (source code here). HashSet is essentially an interface to a HashMap's keySet.
/**
* HashSet is an implementation of a Set. All optional operations (adding and
* removing) are supported. The elements can be any objects.
*/
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable,
Serializable {
private static final long serialVersionUID = -5024744406713321676L;
transient HashMap<E, HashSet<E>> backingMap; // right here!
精彩评论