The ArrayList.contains() method is used to check whether the specified element exists in the given arraylist. If the element exists, then contains() returns true
, else returns false
.
1. Check if Element Exists using ArrayList.contains()
The contains()
method is pretty simple. It simply checks the index of element in the list. If the index is greater than '0'
then the element is present in the list.
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
In the given Java program, we have a few alphabets stored in the arraylist. We will try to find out if letters “A” and “Z” are present in the list or not.
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
2. Using ArrayList.indexOf()
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 existence of any supplied element value.
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: ArrayList Java Docs