What is HashSet in Java?

A HashSet in Java is a collection that implements the Set interface, backed by a hash table. It is one of the simplest and most commonly used collection classes. The main features of HashSet include the ability to store unique elements, fast retrieval of elements, and null support. HashSet does not guarantee any specific order of the elements, which means that the order could vary over time.

Key Features of HashSet:

  • Stores unique elements
  • Allows one null element
  • Does not maintain any order of elements
  • Faster operations for large data sets

Example of HashSet in Java:

import java.util.HashSet; public class HashSetExample { public static void main(String[] args) { HashSet set = new HashSet<>(); // Adding elements to HashSet set.add("Apple"); set.add("Banana"); set.add("Cherry"); set.add("Apple"); // Duplicate element // Displaying the HashSet System.out.println(set); } }

HashSet Java Collection Set Unique Elements