Monday, April 18, 2011

How is set implemented in java?

You know what a "Set" is in java. Its an interface which extends collection interface. It contains no duplicate elements i.e., no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. All is fine and cool until here.
But the question is how set maintains unique elements? Here is how. Internally set maintains a Map when a Set (HashSet/Treeset/etc) is instantiated. See below code of HashSet constructor.

/**
 * Constructs a new, empty set; the backing HashMap instance has
 * default initial capacity (16) and load factor (0.75).
 */
public HashSet() {
    map = new HashMap();
}

So HashSet creates an instance of HashMap when HashSet is instantiated, TreeSet creates an instance of TreeMap when TreeSet is instantiated and so on. The keys in the map are the elements you add to Set. Then what are values? Values are dummy objects. When you add an element to the Set, the element will be added as key and "new Object()" (dummy Object instance) will be added as value which is a dummay value. What will happen if you add a duplicate object to Set? If the set already contains the element, the call to add method leaves the set unchanged and returns false. If the set does not contain the element, the call to add method adds the element and returns true.

No comments:

Post a Comment

Chitika