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.
Syntax:
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.
Steps:
- 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.
Example:
Java
// Java program to check whether an element // is present in an ArrayList // importing package import java.util.*; class GFG { public static void main(String[] args) { // Creating an ArrayList of String type List<String> GFG = new ArrayList<String>(); // Adding elements to the ArrayList GFG.add( "Welcome" ); GFG.add( "To" ); GFG.add( "Geeks" ); GFG.add( "For" ); GFG.add( "Geeks" ); // Using contains() method to check whether the // particular // element is present in the List or not System.out.println(GFG.contains( "Welcome" )); System.out.println(GFG.contains( "Java" )); } } |
true false