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.
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 listArrayList<Integer> arrlist = new ArrayList<Integer>(4);// populate the listarrlist.add(10);arrlist.add(20);arrlist.add(30);arrlist.add(40);// check for presence of an element contained in the listboolean 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 listboolean 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");}}}
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 arrayInteger arr[] = { 10, 20, 30, 40 };// check for presence of an element in the arrayboolean 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 Arrayboolean 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");}}}
Free Resources