Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

HashSet.contains(Object) — test whether an element is present

`contains` checks whether a `HashSet` holds an element equal to the argument. It returns `true` or `false` without changing the set.

Version: Java SE 21

Syntax

public boolean contains(Object o)
boolean present = set.contains(candidate);

In Java SE 21, HashSet.contains(Object) in java.util.HashSet returns true if the set holds an element e for which Objects.equals(o, e) is true. Otherwise, it returns false. What matters is equality, not whether the two references point to the same object. The method does not add or remove anything.

The parameter o is of type Object, not E. You can therefore query a HashSet<String> with an Integer, even though you cannot insert it with add. That query returns false in the example because the Integer is not equal to any stored string. HashSet allows null: contains(null) returns true only if the set contains null.

The lookup uses a hash table and takes constant time when hash codes distribute elements well across its buckets. If you override equals, also override hashCode: equal objects must have the same hash code, but matching hash codes do not imply equality.

While an object is in the set, do not change data that affects equals or hashCode. After such a change, contains might fail to find even that same object.

Examples

import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        HashSet<String> words = new HashSet<>();
        words.add("java");

        System.out.println(words.contains(new String("java")));
        System.out.println(words.contains("JAVA"));
        System.out.println(words.contains(Integer.valueOf(42)));
        System.out.println(words.contains(null));

        words.add(null);
        System.out.println(words.contains(null));
    }
}

Result

true
false
false
false
true

`new String("java")` deliberately creates a separate object with the same text. String equality is case-sensitive, so `"JAVA"` does not match. The `Integer` query is valid but returns `false`. The `null` query returns `false` before `add(null)` and `true` afterward.

Related lessons

  • Java · Lesson 55 · Basic · Version: 2

Sources