Java ArrayList contains() – Check if element exists

ArrayList contains() method is used to check if the specified element exists in the given arraylist or not. If element exist then method returns true, else false.

1. ArrayList contains() syntax

The contains() method is pretty simple. It simply checks the index of element in the list. If the index is greater than '0' than element is present in the list.

public boolean contains(Object o) {
    return indexOf(o) >= 0;
}

2. ArrayList contains() example to check element exists

In given Java program, we have few alphabets stored in the arraylist. We will try to find out if letter “A” and “Z” are present in the list or not.

public class ArrayListExample 
{
    public static void main(String[] args) 
    {
        ArrayList<String> list = new ArrayList<>(2);
        
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        
        System.out.println( list.contains("A") );       //true
        
        System.out.println( list.contains("Z") );       //false
    }
}

Program output.

true
false

3. ArrayList indexOf() example to check if element exists

As noted above, contains() method uses indexOf() method to determine if a specified element is present in the list or not. So we can also directly use the indexOf() method to check the existance of any supplied element value.

public class ArrayListExample 
{
    public static void main(String[] args) 
    {
        ArrayList<String> list = new ArrayList<>(2);
        
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        
        System.out.println( list.indexOf("A") > 0 );       //true
        
        System.out.println( list.indexOf("Z") > 0);       //false
    }
}

Program output.

true
false

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.