Sobes.tech
Junior

What is HashSet in Java?

sobes.tech AI

Answer from AI

HashSet is an implementation of the Set interface that uses a hash table to store elements.

Key features:

  • Unordered: Elements are not stored in a specific order. The iteration order may change.
  • No duplicates: Does not allow storing duplicate elements. Adding an existing element does not affect the set.
  • Performance: Operations like add, remove, and contains are generally performed in constant time (O(1)), assuming a good hash function. In the worst case (with strong collisions), performance can degrade to O(n).
  • null element: Can contain one null element.
  • Thread safety: Not thread-safe by default. For multithreaded environments, you can use Collections.synchronizedSet(new HashSet<E>()) or ConcurrentHashMap.newKeySet().

Internally, HashSet uses an instance of HashMap, where the set elements are keys, and the values are dummy objects (essentially any object ignored by HashSet).

When adding an element e, the hashCode() method of the element is called to determine the bucket in the hash table. Then, the element is compared with existing elements in that bucket using the equals() method. If the element already exists (both hash codes are equal and equals returns true), the element is not added.

Example usage:

// Creating a HashSet
HashSet<String> fruits = new HashSet<>();

// Adding elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Apple"); // Duplicate, will not be added

// Checking if an element exists
boolean hasBanana = fruits.contains("Banana"); // true

// Removing an element
fruits.remove("Orange");

// Iterating over elements
for (String fruit : fruits) {
    System.out.println(fruit); // Order may be arbitrary
}