Introduction

HashSet is implementation of Set interface. Important points about HashSet class are:

  • Stores the elements using hashing.
  • It doesn’t maintain any order, the elements would be returned in any random order.
  • It doesn’t allow duplicates. If you try to add a duplicate element in HashSet, the old value would be overwritten.
  • It is non-synchronized.
  • The iterator returned by this class is fail-fast which means iterator would throw ConcurrentModificationException if HashSet has been modified after creation of iterator, by any means except iterator’s own remove method.

Example

public class HashSetExample { 
  public static void main(String args[]) { 
  
  // HashSet declaration 
  HashSet<String> hset = new HashSet<String>(); 
  
  // Adding elements to the HashSet 
  hset.add("Apple"); 
  hset.add("Mango"); 
  hset.add("Grapes"); 
  
  // Addition of duplicate elements 
  hset.add("Apple"); 
  hset.add("Mango"); 
  
  // Addition of null values 
  hset.add(null); 
  
  // Remove "Easy" from set 
  boolean isremoved = hset.remove("Easy"); 
  
  // Iterating 
  Iterator<String> it = hset.iterator(); 
  
  while(it.hasNext()){ 

  // Retrieves values from HashSet using Iterator 
    System.out.println(it.next()); 
  } 
  
  // Displaying HashSet elements 
  System.out.println(hset); 
  } 
}

Output:
[null, Mango, Grapes, Apple, Orange, Fig]

As you can see there all the duplicate values are not present in the output including the duplicate null value.

Important methods

  • boolean add(E e)
    Adds the specified element to this set if it is not already present.
  • void clear()
    Removes all of the elements from this set.
  • boolean contains(Object o)
    Returns true if this set contains the specified element.
  • boolean isEmpty()
    Returns true if this set contains no elements.
  • Iterator<E> iterator()
    Returns an iterator over the elements in this set.
  • boolean remove(Object o)
    Removes the specified element from this set if it is present.
  • int size()
    Returns the number of elements in this set (its cardinality).
  • public boolean equals(Object o)
    Compares the specified object with this set for equality. Returns true if the given object is also a set, the two sets have the same size, and every member of the given set is contained in this set. This ensures that the equals method works properly across different implementations of the Set interface.
  • public Object[] toArray()
    Returns an array containing all of the elements in this collection. If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.