Java HashSet contains() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashSet

Definition

In Java, contains(o) returns true when a HashSet holds an element equal to o, and false otherwise. It is the main reason to choose a set: the answer comes back quickly even for a huge set.

The set jumps straight to one bucket using o.hashCode(), then compares the few elements there with equals(). Looking for null is allowed and works like any other value.

An instance method of java.util.HashSet (class since Java 1.2): a set of unique elements kept in a hash table, with no guaranteed order, one null element allowed, and no thread safety.

Syntax

One argument; the result is a plain boolean.

Java
Set<String> taken = new HashSet<>();
taken.add("nova");
boolean a = taken.contains("nova");   // true
boolean b = taken.contains("kai");    // false
CallWhat it does
set.contains("nova")true if "nova" is in the set.
if (!set.contains(x)) { ... }Runs only when the element is missing.
set.contains(null)true only if null was added.
set.contains(obj)Uses the equals() of your own class.

The parameter type is Object, not E, so a value of the wrong type compiles but simply returns false.

Library declarations
Java
// java.util.HashSet<E>
public boolean contains(Object o)

// Declared in Set<E> and Collection<E>

Parameters

ParameterDescription
o (Object)The element to look for. It may be null.

Return Value

Return ValueDescription
trueThe set contains an element e where o.equals(e) is true.
falseNo equal element exists, or o has a different type.

Compare with Similar Methods

Other ways to test membership:

MethodHow it differs
containsAll(c)Checks many elements at once.
add(e)Returns false for an element that is already there.
ArrayList.contains(e)Scans the list from the start, so it slows down as the list grows.
HashMap.containsKey(k)The same hash lookup for map keys.

Java Examples

Example 1 — Check Whether a Username Is Taken

Look up three names, including one that differs only by case.

Java
import java.util.HashSet;
import java.util.Set;

public class HashSetContainsDemo {
    public static void main(String[] args) {
        Set<String> taken = new HashSet<>();
        taken.add("nova");
        taken.add("river");
        taken.add("sky");

        System.out.println("nova taken: " + taken.contains("nova"));
        System.out.println("kai taken: " + taken.contains("kai"));
        System.out.println("Nova taken: " + taken.contains("Nova"));

        if (!taken.contains("kai")) {
            taken.add("kai");
        }
        System.out.println("names now: " + taken.size());
    }
}

How It Works

  1. Present. "nova" was added, so the first lookup finds an equal String and prints true.
  2. Absent. Nobody registered "kai", so the lookup returns false.
  3. Case matters. "Nova" has a different hash code and different characters from "nova", so it is not found.
  4. Check, then add. Because "kai" was free, the if block adds it, and the count rises from 3 to 4.

Example 2 — contains() Accepts Any Object, So Types Matter

Search a set of Integer values with an Integer, a long, and a String.

Java
import java.util.HashSet;
import java.util.Set;

public class HashSetContainsTypes {
    public static void main(String[] args) {
        Set<Integer> ids = new HashSet<>();
        ids.add(1);
        ids.add(2);
        ids.add(3);

        System.out.println("contains(2): " + ids.contains(2));
        System.out.println("contains(2L): " + ids.contains(2L));
        System.out.println("contains(\"2\"): " + ids.contains("2"));
        System.out.println("contains(null): " + ids.contains(null));
    }
}

How It Works

  1. Boxing makes a match. The int 2 is boxed to Integer 2, which equals the stored element.
  2. A Long is a different type. 2L boxes to Long, and Integer.equals(Long) is always false, so the answer is false without any warning from the compiler.
  3. A String never equals an Integer. The text "2" looks the same when printed but is a different type, so it is not found.
  4. Null is a normal question. Nobody added null, so HashSet answers false instead of throwing.

Example 3 — Filter a Sentence Against a Blocklist

Check each word of a message against a set of blocked words, ignoring case.

Java
import java.util.HashSet;
import java.util.Set;

public class HashSetContainsBlocklist {
    public static void main(String[] args) {
        Set<String> blocked = new HashSet<>();
        blocked.add("spam");
        blocked.add("scam");

        String message = "Free SPAM and a real offer";
        int hits = 0;

        for (String word : message.split(" ")) {
            if (blocked.contains(word.toLowerCase())) {
                System.out.println("blocked: " + word);
                hits++;
            }
        }
        System.out.println("blocked words found: " + hits);
    }
}

How It Works

  1. Split into words. split(" ") produces six words, and each one is looked up in the two-word blocklist.
  2. Normalise first. toLowerCase() turns "SPAM" into "spam" before the lookup; without it the match would fail because contains() is case-sensitive.
  3. One hit. Only "SPAM" matches, and the original spelling is printed; "Free", "and", "a", "real", and "offer" return false.
  4. Fast for big lists. Each lookup goes to one bucket, so the same loop would stay quick with thousands of blocked words.

Frequently Asked Questions

Call set.contains(element). It returns true when an equal element is in the set and false otherwise.
Constant time on average: the set goes to one bucket from the hash code and compares only the few elements stored there.
For strings, yes. "Java" and "java" are different elements. Convert with toLowerCase() before adding and before searching if you want to ignore case.
The argument has a different type, such as a Long searched in a Set<Integer>, or your class does not override equals() and hashCode().
Yes. set.contains(null) is true only if null was added earlier. HashSet does not throw for null here.

Next: containsAll()

Check that every element of another collection is present.

containsAll() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful