Java List contains() example

In this guide, you will learn about the List contains() method in Java programming and how to use it with an example.

1. List contains() Method Overview


The contains() method of the Java List interface is used to determine if a list contains a specified element.


list.contains(Object o)


Object o - the element whose presence in this list is to be tested.

Key Points:

- Returns true if the list contains the specified element, otherwise false.

- Uses the equals() method to check for equality, so custom objects should have an appropriate equals() implementation.

- The method will return false if the provided element is null and the list doesn't allow null elements.

2. List contains() Method Example

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

public class ListContainsExample {
    public static void main(String[] args) {
        // Create a new ArrayList with some elements
        List<String> fruits = new ArrayList<>();
        System.out.println(fruits.contains("Banana"));  // Outputs: true
        System.out.println(fruits.contains("Grape"));   // Outputs: false

        // Working with custom objects
        class Fruit {
            private final String name;
            public Fruit(String name) { = name; }
            public boolean equals(Object o) {
                if (this == o) return true;
                if (o == null || getClass() != o.getClass()) return false;
                Fruit fruit = (Fruit) o;
                return name.equals(;
        List<Fruit> fruitList = new ArrayList<>();
        fruitList.add(new Fruit("Apple"));
        System.out.println(fruitList.contains(new Fruit("Apple")));  // Outputs: true




In the provided example:

1. We initiated an ArrayList of strings with three fruit names.

2. We then used the contains() method to check if certain fruits were present in the list.

3. In the latter part of the example, we created a custom Fruit class with an equals() method. We showcased how contains() works effectively with custom objects when they have an appropriate equals() implementation.

The contains() method offers a simple way to verify the presence of an element in a list. Still, it's vital to remember its reliance on the equals() method for proper functionality.

Related Java List methods

Java List add() example
Java List clear() example
Java List contains() example
Java List get() example
Java List indexOf() example
Java List remove() example
Java List size() example
Java List toArray() example