Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Collections

Java List.contains() and indexOf() methods

Reference for Java List.contains(), indexOf() and lastIndexOf(): search a list with equals(), the -1 result, custom objects, and faster alternatives.

contains(Object) tells you whether a list holds an element, indexOf(Object) returns the position of the first match and lastIndexOf(Object) the position of the last one. They return false or -1 when nothing matches. All three scan the list from one end and compare with equals().

Because they rely on equals(), searching for your own objects only works if the class overrides it (records do this for you). They also take time proportional to the list length, so for many lookups a HashSet is a better tool.

Java
if (names.contains("Ana")) { ... }
int i = names.indexOf("Ben");

Try it

Java Searching a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java equals() decides the match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
boolean contains(Object o)
int indexOf(Object o)
int lastIndexOf(Object o)
Name Description
o The element to look for, compared with o.equals(element) (or == for null).

Returns: contains returns a boolean; indexOf and lastIndexOf return the zero-based index or -1.

Throws: NullPointerException when searching for null in a list that forbids null (List.of()); ClassCastException in rare lists restricted to certain types.

Usage notes

  • Complexity: O(n) in ArrayList and LinkedList. For repeated membership tests convert to a HashSet or keep a set alongside.
  • equals() is used, not ==, so equal strings or records match even if they are different objects.
  • Type matters: List<Integer>.contains(2L) is false because Long is never equal to Integer.
  • Case-sensitive for strings. For case-insensitive search use a stream with equalsIgnoreCase.
  • Searching by a field: use stream().anyMatch(...) or a loop; contains needs a whole matching element.
  • Sorted lists: Collections.binarySearch() is O(log n) and returns a negative value encoding the insertion point on a miss.
  • Do not confuse with String.contains(), which tests for a substring.