Posts

How HashSet Works Internally In Java?

Image
HashSet  uses HashMap internally to store it’s objects. Whenever you create a HashSet object, one  HashMap  object associated with it is also created. This HashMap object is used to store the elements you enter in the HashSet. The elements you add into HashSet are stored as  keys  of this HashMap object. The value associated with those keys will be a  constant . Every constructor of HashSet class internally creates one HashMap object. You can check this in the source code of HashSet class in JDK installation directory. Below is the some sample code of the constructors of HashSet class. private transient HashMap<E,Object> map; //Constructor - 1 public HashSet() { map = new HashMap<>();//Creating internally backing HashMap object } //Constructor - 2 public HashSet(Collection<? extends E> c) { map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16)); //Creating internally backing HashMap object addAll(c); } //Constructor - 3 public HashSet(in