JavaData StructuresBeginner

HashSet.add() / contains() / remove()

The core methods for adding, checking for existence, and deleting elements in a HashSet, ensuring uniqueness and providing efficient O(1) average time complexity.

Review the syntaxStudy the examplesOpen the coding app
HashSet<E> set = new HashSet<>();
boolean set.add(E e)
boolean set.contains(Object o)
boolean set.remove(Object o)

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

The core methods for adding, checking for existence, and deleting elements in a HashSet, ensuring uniqueness and providing efficient O(1) average time complexity.

A `HashSet` in Java is an implementation of the `Set` interface, which stores unique elements and does not maintain any specific order. It is backed by a `HashMap`, where each element added to the `HashSet` acts as a key in the internal `HashMap`, and a dummy `Object` is used as the value. The `add(E e)` method attempts to add the specified element to the set. It returns `true` if the element was not already present and was successfully added, and `false` otherwise (if the element already exists). The `contains(Object o)` method checks if the set contains the specified element, returning `true` if it does and `false` if not. The `remove(Object o)` method deletes the specified element from the set. It returns `true` if the element was present and successfully removed, and `false` if the element was not found. All three operations (`add`, `contains`, `remove`) offer an average time complexity of O(1) (constant time), making `HashSet` highly efficient for operations requiring fast lookups and uniqueness guarantees. In the worst case (due to hash collisions), complexity can degrade to O(n). `HashSet` allows one `null` element. It is not thread-safe; for concurrent access, `ConcurrentHashMap` or `Collections.synchronizedSet()` should be used.

Quick reference

Syntax

HashSet<E> set = new HashSet<>();
boolean set.add(E e)
boolean set.contains(Object o)
boolean set.remove(Object o)

Inputs

Parameters

eE · The element to be added to this set.
oObject · The element whose presence in this set is to be tested or removed.

See it in practice

Examples

1

Adding unique elements to a HashSet

import java.util.HashSet;

HashSet<String> uniqueNames = new HashSet<>();
System.out.println("Add Alice: " + uniqueNames.add("Alice"));
System.out.println("Add Bob: " + uniqueNames.add("Bob"));
System.out.println("Add Alice again: " + uniqueNames.add("Alice")); // Returns false
System.out.println("Current names: " + uniqueNames);
Output:
Add Alice: true Add Bob: true Add Alice again: false Current names: [Alice, Bob] (order may vary)

Demonstrates that `add()` returns `true` for new elements and `false` for duplicates, ensuring only unique elements are stored.

2

Checking for element existence

import java.util.HashSet;

HashSet<Integer> numbers = new HashSet<>();
numbers.add(10);
numbers.add(20);

System.out.println("Contains 10: " + numbers.contains(10));
System.out.println("Contains 30: " + numbers.contains(30));
Output:
Contains 10: true Contains 30: false

Uses `contains()` to efficiently check if specific elements are present in the set.

3

Removing elements from a HashSet

import java.util.HashSet;

HashSet<String> colors = new HashSet<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");

System.out.println("Original colors: " + colors);

System.out.println("Remove Green: " + colors.remove("Green")); // Returns true
System.out.println("Remove Yellow: " + colors.remove("Yellow")); // Returns false
System.out.println("Colors after removal: " + colors);
Output:
Original colors: [Red, Green, Blue] (order may vary) Remove Green: true Remove Yellow: false Colors after removal: [Red, Blue] (order may vary)

Shows how `remove()` deletes an element and returns `true` if the element was found and removed, `false` otherwise.

Debug faster

Common Errors

1

Incorrect `equals()` and `hashCode()` for custom objects

Cause: When storing custom objects in a `HashSet`, if `equals()` and `hashCode()` methods are not correctly overridden, `HashSet` may fail to recognize duplicate objects or find existing objects, leading to unexpected behavior.

Fix: Always override both `equals()` and `hashCode()` consistently for any custom class whose objects will be stored in a `HashSet` (or `HashMap`). Modern IDEs can auto-generate these methods.

import java.util.HashSet;

class Person {
    String name;
    int id;
    public Person(String name, int id) { this.name = name; this.id = id; }
    // No equals() or hashCode() overridden
}

HashSet<Person> people = new HashSet<>();
people.add(new Person("Alice", 1));
people.add(new Person("Alice", 1)); // This will be added as a distinct object!
System.out.println("Size with incorrect overrides: " + people.size()); // Output: 2

// Fix: Override equals() and hashCode() in Person class
// @Override
// public boolean equals(Object o) {
//     if (this == o) return true;
//     if (o == null || getClass() != o.getClass()) return false;
//     Person person = (Person) o;
//     return id == person.id && Objects.equals(name, person.name);
// }
// @Override
// public int hashCode() {
//     return Objects.hash(name, id);
// }

Runtime support

Compatibility

JVMN/AJava 1.2+

Source: Oracle Java Documentation

Common questions

Frequently Asked Questions

The core methods for adding, checking for existence, and deleting elements in a HashSet, ensuring uniqueness and providing efficient O(1) average time complexity.

e: The element to be added to this set. o: The element whose presence in this set is to be tested or removed.

Incorrect `equals()` and `hashCode()` for custom objects: Always override both `equals()` and `hashCode()` consistently for any custom class whose objects will be stored in a `HashSet` (or `HashMap`). Modern IDEs can auto-generate these methods.