How to Check whether Element Exists in Java ArrayList?
Java ArrayList is a resizable array, which can be found in java.util package. We can add or delete elements from an ArrayList whenever we want, unlike a built-in array.
We can check whether an element exists in ArrayList in java in two ways:
- Using contains() method
- Using indexOf() method
Method 1: Using contains() method
The contains() method of the java.util.ArrayList class can be used to check whether an element exists in Java ArrayList.
public boolean contains(Object)
- object – element whose presence in this list is to be tested
Returns: It returns true if the specified element is found in the list else it returns false.
5 does not exist in the ArrayList 2 exists in the ArrayList
Method 2: Using indexOf() method
- 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.
5 exists in the ArrayList 8 does not exist in the ArrayList
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.