HashSet in Java


We will cover following points of Hashset in Java:

  1. Basics of Hashset in Java
  2. How to iterate through Hashset in Java
  3. Constructor and methods of Hashset in Java

Basics of Hashset in Java

  1. HashSet is a class which implements Set, Cloneable, and Serializable interface but not RandomAccess interface.
  2. HashSet used to store the different types of elements.
  3. HashSet stores the element in an unordered way.
  4. In HashSet, none of the methods are Synchronized.
  5. HashSet uses indexing representation to store the element.
  6. HashSet doesn’t allow the duplicate elements.
  7. HashSet elements can be accessed randomly.
  8. HashSet element can be accessed by using Iterator but it can’t be accessed by using ListIterator.
  9. We can have null in HashSet.

How to iterate Hashset in Java

import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class HashSetExample {
     public static void main(String[] args) {
            Set<String> setObject = new HashSet<>();
            setObject.add("Nadeem");
            setObject.add("Puneet");
            setObject.add("Shyam");
            setObject.add("Jagdish");
            setObject.add("Aakash");
            setObject.add("Nadeem");// duplicates are not allowed and it will not give any compilation error
     Iterator<String> it = setObject.iterator();
       while (it.hasNext()) {
         System.out.println(it.next());
       }
     }
}

Constructor and methods of HashSet in Java

HashSet has mainly four constructor:

  • HashSet()
  • HashSet(Collection c)
  • HashSet(int initialCapacity)
  • HashSet(int initialCapacity, float loadFactor, boolean dummyValue)

Learn more about collection in java


%d bloggers like this: