Java

Java – HashSet With Examples

This class implements the HashTable-backed Set interface (actually a HashMap instance). The set’s iteration order is not guaranteed by it. This indicates that the Java HashSet components’ iteration order is not consistent. The null element is permitted by this class.

Points to Note about HashSet:

  • HashSet utilizes the Hashtable data structure internally.
  • The items would be returned in any arbitrary sequence since HashSet doesn’t preserve any kind of order.
  • Duplicates are not allowed in a hash set. In a hash set, the old value would be replaced if you attempted to add a duplicate entry.
  • HashSet permits null values, however if you input more than one, the previous null value will be overridden.
  • HashSet lacks synchronization. However, it may be explicitly synchronized in the following way: synchronizedSet(new HashSet(…)); Set s = Collections;
  • The iterator that this class returns is fail-fast, which means that if the HashSet is changed after the iterator was created by any method other than the iterator’s own remove function, the iterator will throw the ConcurrentModificationException.

A Simple Example of HashSet in Java

import java.util.HashSet;
public class JavaExample {
  public static void main(String args[]) {
    // HashSet declaration
    HashSet<String> hSet = new HashSet<>();

    // Adding elements to the HashSet
    hSet.add("Cricket");
    hSet.add("Hockey");
    hSet.add("Basketball");

    System.out.println("HashSet Elements: ");
    // Iterating HashSet
    for(String s: hSet){
      System.out.println(s);
    }
  }
}

Output:

HashSet in Java Example

HashSet class Hierarchy

AbstractSet class is extended by HashSet class. The Set interface, which extends the Collection interface, is implemented by the AbstractSet class. You may see this hierarchy as follows:

HashSet -> AbstractSet -> Set -> Collection -> Iterable

HashSet Declaration

The Java.util package contains the HashSet class. HashSet’s Java declaration is as follows:

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable

Initial Capacity and Load Factor:

Initial capacity is the number of data buckets that were initially assigned to HashSet; it automatically rises when HashSet fills up.

The load factor calculates the hashSet’s load and indicates how full the hashSet is. When HashSet is 60% filled, its capacity is automatically expanded, according to a load factor of.60.

                         Number of element in HashSet
Load Factor Of HashSet = ----------------------------
                         Size of the HashSet

Constructors of Java HashSet Class

Constructor Description
HashSet() It builds an empty HashSet with initial capacity of 16 and load factor of .75.
Example: HashSet<String> hSet = HashSet<>();
HashSet(int initialCapacity) It builds an empty HashSet with the specified initial capacity. The default load factor remains .75.
HashSet(int initialCapacity, float loadFactor) It builds an empty HashSet with the specified initial capacity and load factor.
HashSet(Collection) This doesn’t create an empty HashSet. It creates the HashSet with the elements copied from the passed Collection.

Java HashSet Examples

Let’s look at few HashSet in Java samples.

1. Adding duplicate elements

Duplicate values are discarded by HashSet.

import java.util.HashSet;
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");
      hset.add("Orange");
      hset.add("Fig");
      //Addition of duplicate elements
      hset.add("Apple");
      hset.add("Mango");
      //Addition of null values
      hset.add(null);
      hset.add(null);

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

Output:

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

As you can see, every duplicate value—including the duplicate null value—is absent from the output.

2. Removing elements

import java.util.HashSet;
public class JavaExample {
  public static void main(String args[]) {
    // HashSet declaration
    HashSet<String> hSet = new HashSet<>();

    // Adding elements to the HashSet
    hSet.add("AA");
    hSet.add("BB");
    hSet.add("CC");
    hSet.add("DD");
    hSet.add("EE");

    //removing elements
    hSet.remove("EE");
    hSet.remove("CC");

    System.out.println("HashSet Elements: ");
    // Iterating HashSet
    for(String s: hSet){
      System.out.println(s);
    }
  }
}

Output:

HashSet Elements: 
AA
BB
DD

3. Adding elements from other Collection

import java.util.*;
public class JavaExample {
  public static void main(String args[]) {
    //ArrayList declaration and and adding elements
    ArrayList<String> arrList=new ArrayList<>();
    arrList.add("AA");
    arrList.add("BB");
    arrList.add("CC");

    //copying ArrayList elements to HashSet
    HashSet<String> hSet=new HashSet(arrList);
    //adding another element to HashSet after copy
    hSet.add("DD");

    System.out.println("HashSet elements: ");
    Iterator<String> it= hSet.iterator();
    while(it.hasNext())
    {
      System.out.println(it.next());
    }
  }
}

Output:

HashSet elements: 
AA
BB
CC
DD

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button