Categories: Java

HashSet class in Java Collection Framework

The Java HashSet class is used to create a collection that stores data in a hash table. It derives from AbstractSet and implements the Set interface.

This class allows for the null element. The class also provides constant time performance for fundamental operations such as add, delete, contains, and size, assuming the hash function properly distributes the elements throughout the buckets, as we will see later in the article.

Declaration of the Java HashSet class:
public class HashSet<E>extends AbstractSet<E>implements Set<E>, Cloneable, Serializable
The following are the key features of the Java HashSet class:
  • HashSet uses a process known as hashing to store the elements.
  • HashSet only contains unique elements.
  • HashSet accepts null values.
  • The HashSet class does not support synchronization.
  • The insertion order is not preserved by HashSet. Elements are put here based on their hashcode.
HashSet Constructors:
  • HashSet(): It is used to construct a default HashSet.
  • HashSet(Collection c): It is used to populate the hash set with elements from the collection c.
  • HashSet(int capacity): It is used to set the hash’s capacity to the specified integer value capacity. As elements are added to the HashSet, the capacity grows automatically.
HashSet Method:
Modifier & TypeMethodDescription
booleanadd(E e)If the supplied element does not already exist in this set, it is added.
voidclear()It is used to remove all of the set’s elements.
objectclone()It is used to return a shallow replica of this HashSet instance, with no cloning of the elements.
booleancontains(Object o)It is used to return true if the supplied element is present in this set.
booleanisEmpty()It returns true if this set includes no elements.
Iterator<E>iterator()It is used to return an iterator across the set’s elements.
booleanremove(Object o)If the specified element is present, it is removed from this set.
intsize()It returns the number of elements in the set.
Spliterator<E>spliterator()It is used to construct a late-binding and fail-fast Spliterator across the set’s elements.
Example: Adding Elements to HashSet

import java.io.*;
import java.util.*;

// Main class
// AddingElementsToHashSet
class Coderz {

 public static void main(String[] args)
 {
  // Creating an empty HashSet of string entities
  HashSet<String> hobj = new HashSet<String>();

  // Adding elements using add() method
  hobj.add("coderzpy.com");
  hobj.add("For");
  hobj.add("coding");

  // Printing all string el=ntries inside the Set
  System.out.println("HashSet elements : " + hobj);
 }
}
Output:
HashSet elements : [coding, For, coderzpy.com]
Example: Removal Of Elements of HashSet

import java.io.*;
import java.util.*;

class Coderz {

 // Main driver method
 public static void main(String[] args)
 {
  // Creating an
  HashSet<String> hobj = new HashSet<String>();

  // Adding elements to above Set
  // using add() method
  hobj.add("Apple");
  hobj.add("Banana");
  hobj.add("Cat");
  hobj.add("A");
  hobj.add("B");
  hobj.add("Z");

  // Printing the elements of HashSet elements
  System.out.println("Initial HashSet " + hobj);

  // Removing the element B
  hobj.remove("B");

  // Printing the updated HashSet elements
  System.out.println("After removing element " + hobj);

  // Returns false if the element is not present
  System.out.println("Element AC exists in the Set : "
      + hobj.remove("AC"));
 }
}
Output:
Initial HashSet [A, Apple, B, Cat, Z, Banana]
After removing element [A, Apple, Cat, Z, Banana]
Element AC exists in the Set : false
Example: Iteration Over HashSet

import java.io.*;
import java.util.*;

class Coderz {

 // Main driver method
 public static void main(String[] args)
 {

  // Creating an empty HashSet of string entries
  HashSet<String> hobj = new HashSet<String>();

  // Adding elements to above Set
  // using add() method
  hobj.add("Coderzpy.com");
  hobj.add("is fun");
  hobj.add("for coding");
  hobj.add("A");
  hobj.add("B");
  hobj.add("Z");

  // Iterating though the HashSet using iterators
  Iterator itr = hobj.iterator();

  // Holds true till there is single element
  // remaining in Set
  while (itr.hasNext())

   // Traversing elements and printing them
   System.out.print(itr.next() + ", ");
  System.out.println();

  // Using enhanced for loop for traversal
  for (String s : hobj)

   // Traversing elements and printing them
   System.out.print(s + ", ");
  System.out.println();
 }
}
Output:
A, B, Coderzpy.com, for coding, is fun, Z, 
A, B, Coderzpy.com, for coding, is fun, Z, 

Note: also read about the Map Interface in Java Collection Framework

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago