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.
Below image illustrates the hierarchy of Java HashSet class.
Java HashSet class hierarchy
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.
Let’s have a look into most commonly used HashMap methods with simple examples.
Adds the specified element to this set if it is not already present. If an element was added, the method returns true, otherwise false.
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.
Returns the number of elements in this set (its cardinality).
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.
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.
Removes all of the elements from this set. We can use this method to empty the current set.
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.