HashSet in java basics and internal working

HashSet in java is part of the Collection framework and implements the Set interface.
Few points to remember about HashSet
1. HashSet internally uses HashMap to store elements/objects
2. HashSet stores unique values and one null is allowed
3. HashSet doesn’t guarantee the insertion order of the elements. Use LinkedHashSet for that purpose.
4. HashSet doesn’t guarantee the sorting of the elements. Use TreeSet for that purpose.
5. HashSet is not a Synchronized collection. You can use the Collections.synchronizedSet or CopyOnWriteArraySet for this.

HashSet in java basics and internal working

How HashSet in java internally works

HashSet internally uses the HashMap for storing elements/objects. In the below code ( HashSet source code) you can see that a HashMap is used and initialized inside the constructor of the HashSet.

How add works

When you add an element/object in HashSet, it calls the HashMap.put method and adds the element as the KEY. A static object PRESENT is used as VALUE of the hashmap.

So if any duplicate value is added, the map will return false and no value gets added.

How remove works

When you remove an element/object from HashSet, it calls the HashMap.remove method and removes that specified element.

Constructors

HashSet()
Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).
HashSet(Collection c)
Constructs a new set containing the elements in the specified collection.
HashSet(int initialCapacity)
Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and default load factor (0.75).
HashSet(int initialCapacity, float loadFactor)
Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and the specified load factor.

Methods

1. boolean add(E e)
Adds the specified element to this set if it is not already present.
2. void clear()
Removes all of the elements from this set.
3. Object clone()
Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
4. boolean contains(Object o)
Returns true if this set contains the specified element.
5. boolean isEmpty()
Returns true if this set contains no elements.
6. Iterator iterator()
Returns an iterator over the elements in this set.
7. boolean remove(Object o)
Removes the specified element from this set if it is present.
8. int size()
Returns the number of elements in this set (its cardinality).

Reference

1. HashSet in Java docs

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn