Dung (Donny) Nguyen

Senior Software Engineer

HashSet

HashSet in Java is a part of the java.util package and implements the Set interface. It is widely used when we need to store unique elements and do not care about the order in which they are stored.

Key Features of HashSet:

  1. No Duplicate Elements: A HashSet cannot contain duplicate elements, meaning it will automatically filter out any repeated values.

  2. Unordered: The elements are stored in no particular order. The order of insertion is not maintained, as HashSet uses a hashing mechanism.

  3. Null Elements: A HashSet can contain at most one null element.

  4. Efficient Lookup: It provides constant-time performance for basic operations like add, remove, contains, and size, assuming the hash function disperses elements properly across the hash table.

  5. Underlying Data Structure: It uses a hash table for storage, meaning it internally relies on the hash code of objects to store and retrieve elements efficiently.

Common Methods:

Example Usage:

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();
        
        // Add elements to the HashSet
        set.add("Apple");
        set.add("Banana");
        set.add("Orange");
        set.add("Banana");  // Duplicate element, will not be added

        // Print the HashSet
        System.out.println(set);  // Output: [Apple, Orange, Banana] (Order may vary)

        // Check if an element exists
        System.out.println(set.contains("Apple"));  // Output: true

        // Remove an element
        set.remove("Banana");

        // Check the size of the set
        System.out.println(set.size());  // Output: 2
    }
}

Advantages:

Limitations: