Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

List.contains(Object) — check whether a list contains an element

Check whether a list holds an element equal to a given value before adding a task name or marking the task complete.

Version: Java SE 21

Syntax

boolean contains(Object o)

boolean present = list.contains(value);

List.contains(Object) is a method of java.util.List. The call list.contains(o) returns true when some element e satisfies Objects.equals(o, e), and false when there is no match. It neither returns an index nor changes the list.

Matching does not require both references to point to the same object. String.equals compares the full character sequence and is case-sensitive: "Review" matches a separate String with the same text, but not "review" or the substring "Rev".

The parameter type is Object, not E, even for a List<String>. For an incompatible argument type, an implementation may return false or throw ClassCastException. If the list permits null, contains(null) returns true only when the list holds null; if it does not permit null, the call may return false or throw NullPointerException.

In single-threaded code, use !tasks.contains(name) before adding a name to a mutable list to avoid a duplicate. Use tasks.contains(name) to check that a name exists before a separate operation marks the task complete.

Examples

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> tasks = new ArrayList<>();
        tasks.add("Review");
        String candidate = new String("Review");

        System.out.println(tasks.contains(candidate));
        System.out.println(tasks.contains("review"));

        if (!tasks.contains(candidate)) {
            tasks.add(candidate);
        }
        System.out.println(tasks.size());
    }
}

Result

true
false
1

`candidate` is a separate object with the same text as the stored element, so the first result is `true`. Changing the first letter's case gives `false`. The condition skips the duplicate, so the list size stays at `1`.

Related lessons

  • Java · Lesson 22 · Intermediate · Version: 2

Sources