HashSet

A HashSet is part of Java’s collection framework and is an implementation of the Set interface. It is a collection that doesn’t allow duplicate elements and stores them in an unordered way. It is backed by a hash table, which means it provides constant time complexity (O(1)) for the basic operations like add, remove, and contains, assuming the hash function disperses the elements properly.

Features

  • No Duplicates: A HashSet automatically removes duplicate elements. If you try to add an element that’s already in the set, it will not be added again.
  • Unordered: The elements in a HashSet are not stored in any particular order. The order in which elements are added is not necessarily the order in which they are iterated.
  • Null Elements: HashSet allows one null element, unlike some other collection types.
  • Fast Performance: Because it uses a hash table, it performs most operations (like add, remove, and contains) in constant time O(1), making it efficient for large datasets.

Common Operations

  • add(E e): Adds the specified element to the set if it’s not already present.
  • remove(Object o): Removes the specified element from the set.
  • contains(Object o): Checks if the set contains the specified element.
  • size(): Returns the number of elements in the set.
  • clear(): Removes all elements from the set.

Example

Use Cases

  • When you need to store a collection of unique elements.
  • When you do not care about the order of elements.
  • When you need to perform fast lookups, additions, or deletions of elements.