Java Program to Check Whether an Element Occurs in a List
The List Interface in Java represents an ordered collection or sequence. This Interface helps us control where to insert elements and also access elements through an integer index. This Interface is a member of the Java Collections Framework and the java.util package. The classes that implement the List Interface include ArrayList, LinkedList, Stack, and Vector. The Vector class has been deprecated since Java 5.
The classes, ArrayList, LinkedList, and Stack, all use the contains() method to check whether an element occurs in the List.
The contains() method of List interface in Java is used for checking if the specified element exists in the given list or not.
public boolean contains(Object obj) object-element to be searched for
Parameters: This method accepts a single parameter obj whose presence in this list is to be tested.
Return Value: It returns true if the specified element is found in the list else it returns false.
- Import the necessary packages. In this case, we need to import the java.util package.
- Create an ArrayList with the help of the List Interface.
- Add elements to the ArrayList using the add() method.
- Check whether the required element occurs in the ArrayList with the help of the contains() method.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.