1

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

1
  • 6
    You could easily answer this yourself by looking at the source code!! Commented Feb 12, 2010 at 5:47

4 Answers 4

6

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Interesting; I had always just assumed it would do put(e,e).
why not just use a null value?
@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.
5

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

3 Comments

What do you mean when you say "keys of maps are sets"?
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.
Or if you look at Map.keySet() it returns a Set.
1

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

Comments

0

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.