Java HashSet : Collection Class



HashSet class :

  1. HashSet does not allows duplicate elements in it.
  2. HashSet extends AbstractSet and implements the Set interface.
  3. HashSet uses Hash Table as data structure

Lets create an HashSet using following line of code –

Example #1 : Create HashSet

package com.c4learn.collection;

import java.util.HashSet;
import java.util.Iterator;

public class HashSetExample {

  public static void main(String[] args) {

    HashSet<String> hSet = new HashSet<String>();
    hSet.add("B");
    hSet.add("A");
    hSet.add("B");
    hSet.add("D");
    hSet.add("C");
    hSet.add("A");
    
    System.out.println("Size of hSet : " + hSet.size());

    Iterator<String> itr = hSet.iterator();
    while (itr.hasNext()) {
      System.out.println(itr.next());
    }
  }
}

Output :

Size of hSet : 4
D
A
B
C

In the above example, we have created an HashSet using the following line –

HashSet<String> hSet = new HashSet<String>();

Example #2 : Create HashSet using ArrayList

package com.c4learn.collection;

import java.util.ArrayList;
import java.util.HashSet;

public class HashSetExample {

  public static void main(String[] args) {
    
    ArrayList<String> arrList = new ArrayList<String>();
    
    arrList.add("X");
    arrList.add("Y");
    arrList.add("Z");
    
    HashSet<String> hSet = new HashSet<String>(arrList);
    
    System.out.println("hSet : " + hSet);
  }

}

Output :

hSet : [Y, X, Z]

In the above example we have created an ArrayList using the following statements –

ArrayList<String> arrList = new ArrayList<String>();
    
arrList.add("X");
arrList.add("Y");
arrList.add("Z");

After that, we pass the ArrayList as an argument to constructor of HashSet.

HashSet<String> hSet = new HashSet<String>(arrList);