Java HashSet - HashSet in Java With Examples

Java HashSet is the most popular implementation of Set interface. java.util.HashSet is backed by a HashMap. HashSet extends AbstractSet class and implements Set, Cloneable and Serializable interfaces.

Java HashSet

Some of the important points about HashSet in java are;

  1. HashSet doesn’t allow duplicate entries.
  2. HashSet allows null as a value.
  3. HashSet doesn’t guarantee the insertion order of elements.
  4. HashSet is not thread-safe. You can get thread-safe HashSet using Collections.synchronizedSet method at the cost of performance. You can also use CopyOnWriteArraySet concurrency class for thread safety.
  5. HashSet iterator methods are fail-fast. So any structural modification to the set after creation of iterator will throw ConcurrentModificationException.
  6. HashSet supports Generics, this is the recommended approach to avoid ClassCastException at runtime.
  7. HashSet uses HashMap for storing elements, so the objects should provide good implementation of hashCode() and equals() method to avoid unwanted results.

Java HashSet Constructors

Java HashSet provides four constructors.

  1. public HashSet(): Creates a new empty HashSet, the backing HashMap is initialized with default initial capacity as 16 and load factor 0.75.
  2. public HashSet(int initialCapacity): Creates a empty HashSet with backing HashMap initialized with specified capacity and load factor 0.75.
  3. public HashSet(int initialCapacity, float loadFactor): Creates a empty HashSet with backing HashMap initialized with specified capacity and specified load factor.
  4. public HashSet(Collection<? extends E> c): Creates a new Set containing the elements in the specified collection. The backing HashMap is created with default load factor (0.75) and an initial capacity sufficient enough to contain all the elements in the specified collection.

Below code snippet is showing all these HashSet constructors example usage.

Java HashSet Methods

Some of the useful HashSet methods are;

  1. public boolean add(E e): Adds the given element to the Set if not already present. This method internally uses equals() method to check for duplicates, so make sure your object defines equals() method properly.
  2. public void clear(): Removes all the elements from the Set.
  3. public Object clone(): Returns a shallow copy of the Set instance.
  4. public boolean contains(Object o): Returns true if the Set contains the given element, othrweise false.
  5. public boolean isEmpty(): Returns true if Set contains no elements, otherwise false.
  6. public Iterator<E> iterator(): Returns an iterator over the elements in this set. The elements are returned in no particular order.
  7. public boolean remove(Object o): Removes the given element from this set if it is present and return true. If the element is not present in the set, just returns false.
  8. public int size(): Returns the number of elements in the set.
  9. public Spliterator<E> spliterator(): Creates a late-binding and fail-fast Spliterator over the elements in this set. This is introduced in Java 8, however I have not used it till now.
  10. public boolean removeAll(Collection<?> c): HashSet inherits this method from AbstractSet. This method will remove all the elements in the set that are part of the specified collection.

Java HashSet Example

Java HashSet example program showing common usage of HashSet in java.

Output of above HashSet example program is given below, I am not explaining them since they are self understood.

Java HashSet ConcurrentModificationException Example

Java HashSet iterator is fail-fast, so it’s methods will throw java.util.ConcurrentModificationException if Set is structurally modified. Below is a simple example demonstrating this.

I am getting below output and exception when above program is executed.

Note that HashSet elements are not guaranteed to be ordered and ConcurrentModificationException is being thrown by iterator.next() call. So if the “Orange” is the last one in the iterator, you will not get the exception because iterator.hasNext() will return false and iterator.next() will not get called.

We should always use Iterator methods for structural modification, as shown in below example code.

Above HashSet iterator example will not throw exception and you will get below output.

Java HashSet to Array Example

Sometimes we have to convert HashSet to array and vice versa. Below is a simple program showing correct way to convert HashSet to array and then Array to HashSet.

Output of above HashSet to array example is;

Java HashSet to List Example

There is not much difference between Set and List, but sometimes we have to convert from Set to List or List to Set. Below is a simple example showing correct way to convert Set to List and then List to Set in java.

Output of above java Set to List example program is;

Java HashSet equals() and hashCode() methods

HashSet utilise HashMap for storing it’s elements. HashSet works with equals() and hashCode() method to check for duplicate element when you try to add an element. Let’s see what happens if you Set object doesn’t provide equals() method implementation.

When we run above program, we get below output for Set elements.

So it looks like we were able to store duplicate elements in the Set. Actually not, it’s happening because Emp class doesn’t define equals() method, so Object class equals() method implementation is used. Object class defines equals() method like below.

So when adding a new element, object reference is being checked rather than content. Hence we have objects with duplicate content, however they are having different references. Let’s see what happens when we define hashCode() and equals() methods in the Emp class.

This time our program produces following output.

Notice that HashSet was able to check for duplicate when we tried to add an element. But we can change the object values using setter methods and make it duplicate. It worked because there is no operation done on Set. This is why Immutable objects works better with Set and Map.

That’s all for Java HashSet example tutorial, I hope that all the important things are covered for HashSet in Java. If I have missed anything, please let me know through comments and I will try to add that too.

By admin

Leave a Reply