HashSet in java

HashSet:

HashSet extends AbstractSet and implements the Set interface. It does not maintain any order for its elements. It uses a hash table for storage.

  • The elements are stored by the HashSet class using the hashing mechanism.
  • Only unique elements are allowed by the HashSet class.
  • Null values are allowed by the HashSet class.
  • It is non-synchronized.
  • The elements of the HashSet class are inserted based on their hashcode, thus this class does not maintain the insertion order.
  • It performs the best in search operations.
  • Its initial default capacity is 16.
  • Its load factor is 0.75.

Hierarchy of HashSet class:

The AbstractSet class is extended by the HashSet class that implements the Set interface. The Collection and Iterable interfaces are inherited by the Set interface in hierarchical order.

HashSet class declaration:

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

HashSet class Constructors:

S.No. Constructor Description
1 HashSet() It will create a default HashSet.
2 HashSet(int capacity) It will create and initialize the capacity of the hash set to the given integer value capacity. As elements are added to the HashSet, the capacity grows automatically.
3 HashSet(int capacity, float loadFactor) It will create and initialize the capacity of the hash set to the given integer value capacity and the specified load factor.
4 HashSet(Collection<? extends E> c) It will create and initialize the hash set by using the elements of the collection c.

HashSet class Methods:

Sl.No. Return Type Method Description
1 boolean add(E e) It will add the specified element to this set if it is not already present.
2 void clear() It will eliminate all of the elements from the set.
3 object clone() It will get a shallow copy of this HashSet instance: the elements themselves are not cloned.
4 boolean contains(Object o) It will get true if this set contains the specified element.
5 boolean isEmpty() It will get true if this set contains no elements.
6 Iterator<E> iterator() It will get an iterator over the elements in this set.
7 boolean remove(Object o) It will eliminate the specified element from this set if it is present.
8 int size() It will get the number of elements in the set.
9 Spliterator<E> spliterator() It will create a late-binding and fail-fast Spliterator over the elements in the set.

HashSet example:

HashSetTest.java

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
 
/**
 * This class is used to show the HashSet functionality.
 * @author w3schools
 */
public class HashSetTest {
	public static void main(String args[]){
		//Create HashSet object.
		Set hashSet = new HashSet();
 
		//Add objects to the HashSet.
		hashSet.add("Roxy");
		hashSet.add("Sunil");
		hashSet.add("Sandy");
		hashSet.add("Munish");
		hashSet.add("Pardeep");
 
		//Print the HashSet object.
		System.out.println("HashSet elements:");
		System.out.println(hashSet);
 
		//Print the HashSet elements using iterator.
		Iterator iterator=hashSet.iterator();
		System.out.println("HashSet elements using iterator:");
		while(iterator.hasNext()){  
		   System.out.println(iterator.next());  
		}  
	}
}

Output

HashSet elements:
[Sandy, Pardeep, Munish, Sunil, Roxy]
HashSet elements using iterator:
Sandy
Pardeep
Munish
Sunil
Roxy

Example: Ignoring duplicate elements:

import java.util.*;  
public class HashSetExample{  
 public static void main(String args[]){  
  //Creating HashSet and adding elements  
  HashSet<string> set=new HashSet<string>();  
  set.add("A");  
  set.add("B");  
  set.add("A");  
  set.add("C");  
  //Traversing elements  
  Iterator<string> itr=set.iterator();  
  while(itr.hasNext()){  
   System.out.println(itr.next());  
  }  
 }  
}

Output:

Example: Different ways to remove an element:

import java.util.*;  
public class HashSetExample{  
 public static void main(String args[]){  
  HashSet<string> set=new HashSet<string>();  
           set.add("A");  
           set.add("B");  
           set.add("C");  
           set.add("D");  
           System.out.println("An initial list of elements: "+set);  
           //Removing specific element from HashSet  
           set.remove("A");  
           System.out.println("After invoking remove(object) method: "+set);  
           HashSet<string> set1=new HashSet<string>();  
           set1.add("E");  
           set1.add("F");  
           set.addAll(set1);  
           System.out.println("Updated List: "+set);  
           //Removing all the new elements from HashSet  
           set.removeAll(set1);  
           System.out.println("After invoking removeAll() method: "+set);  
           //Removing elements on the basis of specified condition  
           set.removeIf(str->str.contains("B"));    
           System.out.println("After invoking removeIf() method: "+set);  
           //Removing all the elements available in the set  
           set.clear();  
           System.out.println("After invoking clear() method: "+set);  
 }  
}

Output:

Example: Java HashSet from another Collection:

import java.util.*;  
public class HashSetExample{  
 public static void main(String args[]){  
   ArrayList<string> list=new ArrayList<string>();  
           list.add("A");  
           list.add("B");  
           list.add("C");  
 
           HashSet<string> set=new HashSet(list);  
           set.add("D");  
           Iterator<string> i=set.iterator();  
           while(i.hasNext())  
           {  
           System.out.println(i.next());  
           }  
 }  
}

Output:

Next Topic: LinkedHashSet in java with example.
Previous Topic: Collection classes in java with example.