views:

220

answers:

4

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

+4  A: 

the key would be the object that went into the hashset itself since keys of maps are sets.

Charles Ma
What do you mean when you say "keys of maps are sets"?
danben
a key of a map will always map to the same value, so all map keys have to be unique. So by definition, they're sets.
Charles Ma
Or if you look at Map.keySet() it returns a Set.
Peter Lawrey
+5  A: 

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;
}
danben
Interesting; I had always just assumed it would do put(e,e).
Software Monkey
why not just use a null value?
dertoni
@dertoni: I didn't write it, of course, but my guess would be that they wanted to allow for a different backing implementation of HashMap, which would not be guaranteed to permit null values.
danben
+1  A: 

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).

Lombo
A: 

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!
oksayt