HashSet Class in Java Tutorial with Example

Java HashSet class implements Set interface. It has the following properties.

1. HashSet does not allow duplicates, means it contains unique elements.
2. HashSet is unordered meaning it does not guarantee that the order will remain constant over time.
3. HashSet is backed by Hashtable (actually a HashMap instance).
4. HashSet permits the null elements.
5. HashSet implementation is not synchronized. It can be synchronized externally.
    Set s = Collections.synchronizedSet(new HashSet(...));
6. Iterators returned by HashSet class is fail- fast.

HashSet Example


import java.util.*;

public class HashSetExample {

   public static void main(String args[]) {

      // Declare HashSet 
      HashSet<String> hashset = 
             new HashSet<String>();

      // Adding elements to the HashSet
      hashset.add("Apple");
      hashset.add("Pear");
      hashset.add("Mango");
      hashset.add("Papaya");
      hashset.add("Orange");
      //Addition of duplicate elements
      hashset.add("Apple");
      hashset.add("Mango");
      //Addition of null values
      hashset.add(null);
      hashset.add(null);

      //Displaying HashSet elements
      System.out.println(hashset);
   }
}

Output :
[null, Apple, Pear, Papaya, Mango, Orange]

HashSet Methods

1. boolean add(Element e) : it adds the element e to the list.
2. public void clear() : it removes all of the elements from the set.
3. public Object clone() : It returns the shallow copy of the HashSet instance.
4. public boolean contains(Object o) : it returns true if the set contains the specified element.
5. public boolean isEmpty() : This method returns true if the set  contains no elements.
6. public boolean remove(Object o) : it removes the specified element from the set if it is present.
7. public int size() : it returns the number of elements in the set.

HashSet Tutorials

Basics


  • How HashSet works in Java
  • HashSet Iterator Example

  • Conversions


  • Convert HashSet to List
  • Convert HashSet to TreeSet
  • Convert HashSet to Array

  • Differences


  • HashSet vs TreeSet
  • HashSet vs HashMap
  • HashSet vs CopyOnWriteArraySet
  • HashSet vs ArrayList 

  • More Interview Questions


  • HashSet Interview Questions



  • References : HashSet Oracle docs



    About The Author

    Subham Mittal has worked in Oracle for 3 years .
    For more java articles ,Click here to Subscribe JavaHungry