What is the ArrayList.contains[] method in Java?
The ArrayList.contains[] method in Java is used to check whether or not a list contains a specific element.
To check if an element is in an array, we first need to convert the array into an ArrayList using the asList[] method and then apply the same contains[] method to it.
Syntax
Code
The following code snippet demonstrates how the contains[] method is used to check the presence of an object in a list:
import java.util.ArrayList;
public class main {
public static void main[String[] args] {
// create an array list
ArrayList arrlist = new ArrayList[4];
// populate the list
arrlist.add[10];
arrlist.add[20];
arrlist.add[30];
arrlist.add[40];
// check for presence of an element contained in the list
boolean retval = arrlist.contains[10];
if [retval == true] {
System.out.println["10 is present in the list"];
} else {
System.out.println["10 is not present in the list"];
}
// check for presence of an element not contained in the list
boolean retval2 = arrlist.contains[90];
if [retval2 == true] {
System.out.println["90 is present in the list"];
} else {
System.out.println["90 is not present in the list"];
}
}
}
Run
To apply the contains[] method to an array, we first need to convert the array into an ArrayList:
import java.util.Arrays;
public class main {
public static void main[String[] args] {
// create an array
Integer arr[] = { 10, 20, 30, 40 };
// check for presence of an element in the array
boolean retval = Arrays.asList[arr].contains[10];
if [retval == true] {
System.out.println["10 is present in the Array"];
} else {
System.out.println["10 is not present in the Array"];
}
// check for presence of an element not in the Array
boolean retval2 = Arrays.asList[arr].contains[90];
if [retval2 == true] {
System.out.println["90 is present in the Array"];
} else {
System.out.println["90 is not present in the Array"];
}
}
}
Run