http://javahungry.blogspot.com/p/interview.
html
http://javahungry.blogspot.com/2014/11/15-good-questions-to-ask-at-an-
interview.html
http://javahungry.blogspot.com/2013/08/how-sets-are-implemented-internally-in.html
http://javahungry.blogspot.com/2013/06/difference-between-equals-and-double-equals-
method-with-example-java-collections-interview-question.html
http://javahungry.blogspot.com/2013/07/threads-lifecycle-example-java-methods-
explanation.html
http://javahungry.blogspot.com/2013/06/difference-between-string-stringbuilder.html
http://javahungry.blogspot.com/2014/02/hashmap-vs-concurrenthashmap-java-
collections-interview-question.html
http://javahungry.blogspot.com/2013/12/difference-between-arraylist-and-vector-in-
java-collection-interview-question.html
public class HashSet<E>
extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable {
private transient HashMap<E, Object> map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public HashSet(){
map = new HashMap<>();
}
// SOME CODE, i.e. other methods in Hash St
public boolean add(E e){
return map.put(e, PRESENT) == null;
}
// SOME CODE, i.e. Other methods in Hash Set
Whenever you create an object of HashSet, an object of HashMap will be created.
In HashMap, each key is unique. So what we do in HashSet is that we pass the
argument in the add(Element E) that is E as a key in the HashMap. In order to pass
stuff into a HashMap, we need an key-value pair, so we pass (E, "a dummy value
called PRESENT").
Now going over to HashMap's put method, which returns null if key is unique and is
added to the map, returns the value of the key if that key is a duplicate
so we check if put() returns a null or not