In this article we will dive into Java HashSet and it’s most commonly used methods. Java HashSet is one of the most commonly used implementation of Set collection interface.

  1. Characteristics of Java HashSet

  1. This class implements the Set interface, the under lying data structure is hash table (actually a HashMap instance).
  2. Insertion order is not preserved and the order is based on hash code of the objects.
  3. Duplicate objects are not allowed.
  4. If we are trying to insert duplicate objects we won’t get compile time error and run-time error, add() method simply returns false, and false means new element not inserted in to set, the old element remains same.
  5. null insertion is possible.
  6. A Java HashSet is non synchronized, means

2. Hierarchy of HashSet class

Below image illustrates the hierarchy of Java HashSet class.

Java HashSet class hierarchy

Java HashSet class hierarchy

3. Creating HashSet instance

Copy to Clipboard

The above code constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75), means a new HashMap creates internally.

Copy to Clipboard

4. Java HashSet methods

Let’s have a look into most commonly used HashMap methods with simple examples.

4.1. add()

Adds the specified element to this set if it is not already present. If an element was added, the method returns true, otherwise false.

Copy to Clipboard

4.2. isEmpty()

Returns true if this set contains no elements, otherwise false. We can use this method to know whether the set has any elements or not.

Copy to Clipboard

4.3. size()

Returns the number of elements in this set (its cardinality).

Copy to Clipboard

4.4. contains()

Returns true if this set contains the specified element. We can use this method to know whether specific element already exist in Set or not.

Copy to Clipboard

4.5. remove()

Removes the specified element from this set if it is present and return true. We can use this method to remove specific element form Set.

Copy to Clipboard

4.6. clear()

Removes all of the elements from this set. We can use this method to empty the current set.

Copy to Clipboard

4.7. iterator()

Returns an iterator over the elements in this set. The elements are returned in no particular order. We can use this method to iterate each element from the set.

Complete Example

Copy to Clipboard

References