CKTIS / Java
Set.contains — test whether a set contains an element
Check whether a set has an element equal to the object you supply, and see why a newly created instance with the same ID can match.
Version: Java SE 21
Syntax
boolean contains(Object o)
boolean present = set.contains(candidate);Set.contains is an instance method of java.util.Set<E>. The call set.contains(candidate) returns true if there is a stored element e for which Objects.equals(candidate, e) is true, and false if there is no match. It neither adds nor returns an element. The test is based on equality, not reference identity (==).
The parameter is Object, not E, so even a Set<Member> can be queried with an object of another type. Depending on the implementation, a query with an incompatible type may return false or throw ClassCastException, and a query with null on a set that disallows it may return false or throw NullPointerException. HashSet permits null: contains(null) is true only if null is stored.
HashSet uses hashCode and equals for lookup. Equal objects must have equal hash codes, but a shared hash code does not establish equality. Do not change data that affects equals while an object is in a set: the set's behavior after such a change is unspecified.
The example's records use the default equals and hashCode. Two Member objects with the same id are equal even if they were created separately. A Guest with the same id is not equal to a Member because it belongs to a different record class.
Examples
import java.util.HashSet;
import java.util.Set;
public class Main {
record Member(int id) {}
record Guest(int id) {}
public static void main(String[] args) {
Set<Member> members = new HashSet<>();
members.add(new Member(100));
System.out.println(members.contains(new Member(100)));
System.out.println(members.contains(new Member(101)));
System.out.println(members.contains(new Guest(100)));
}
}Result
true false false
The first line is `true`: the new `Member(100)` equals the stored element. `Member(101)` has a different ID and `Guest(100)` belongs to a different class, so both remaining lines are `false`.
Related lessons
- Java · Lesson 5 · Advanced · Version: 2
- Java · Lesson 42 · Basic · Version: 2