Java 25 (LTS) reference · List and ArrayList Methods
Java List contains() Method
Return true if the list holds an element equal to the given one (using equals()). O(n) for ArrayList.
Java 25 (LTS) Since Java 1.0
Syntax
list.contains(object)
Parameters
| Parameter | Description |
|---|---|
objectObject |
The value to look for. |
Return value
true or false.
Examples
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> roles = List.of("admin", "editor");
System.out.println(roles.contains("admin"));
System.out.println(roles.contains("viewer"));
}
}
Output
true false
Run this on your computer — see “Get Started” for setup.
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> big = new ArrayList<>();
for (int i = 0; i < 100_000; i++) big.add(i);
Set<Integer> fast = new HashSet<>(big); // contains() on a HashSet is O(1)
System.out.println(big.contains(99_999) + " " + fast.contains(99_999));
}
}
Output
true true
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 1.0 | Added |
Related
list.indexOf()· Return the index of the first element equal to the given one, or -1. lastIndexOf() searches from the end.map.containsKey()· Return true if the map has an entry for the key, even when its value is null. O(1) for HashMap.- Java ArrayList · tutorial