Introduction to Java HashSet: Features and Examples

Answered using GPT-4o-mini by Java Q&A Hub

Question:

Introduce Java HashSet and give examples

Answer:

A HashSet in Java is a part of the Java Collections Framework and implements the Set interface. It is used to store a collection of unique elements, meaning that it does not allow duplicate values. The HashSet class is backed by a hash table, which provides constant time performance for basic operations like add, remove, and contains, assuming the hash function disperses the elements properly among the buckets.

Key Features of HashSet:

  1. No Duplicates: A HashSet does not allow duplicate elements. If you try to add a duplicate, it will simply ignore the operation.
  2. Unordered: The elements in a HashSet are not stored in any particular order. The order can change when elements are added or removed.
  3. Null Values: A HashSet allows one null value.
  4. Performance: It offers constant time performance for basic operations like add, remove, and contains, on average.

Basic Operations:

  • Add: Adds an element to the set.
  • Remove: Removes an element from the set.
  • Contains: Checks if an element is present in the set.
  • Size: Returns the number of elements in the set.
  • Clear: Removes all elements from the set.

Example Code:

Here’s a simple example demonstrating the use of HashSet in Java:

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        // Create a HashSet
        HashSet<String> set = new HashSet<>();

        // Add elements to the HashSet
        set.add("Apple");
        set.add("Banana");
        set.add("Orange");
        set.add("Mango");
        set.add("Apple"); // Duplicate element, will not be added

        // Display the HashSet
        System.out.println("HashSet: " + set);

        // Check if an element exists
        if (set.contains("Banana")) {
            System.out.println("Banana is in the HashSet.");
        } else {
            System.out.println("Banana is not in the HashSet.");
        }

        // Remove an element
        set.remove("Mango");
        System.out.println("After removing Mango: " + set);

        // Get the size of the HashSet
        System.out.println("Size of HashSet: " + set.size());

        // Clear the HashSet
        set.clear();
        System.out.println("After clearing, HashSet: " + set);
    }
}

Output:

HashSet: [Banana, Orange, Apple, Mango]
Banana is in the HashSet.
After removing Mango: [Banana, Orange, Apple]
Size of HashSet: 3
After clearing, HashSet: []

Conclusion:

HashSet is a powerful and efficient way to store unique elements in Java. It is particularly useful when you need to ensure that no duplicates are present and when the order of elements is not important.