 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check existence of an element in Java ArrayList
The java.util.ArrayList.contains() method can be used to check if an element exists in an ArrayList or not. This method has a single parameter i.e. the element whose presence in the ArrayList is tested. Also it returns true if the element is present in the ArrayList and false if the element is not present.
A program that demonstrates this is given as follows
Example
import java.util.ArrayList; import java.util.List; public class Demo { public static void main(String[] args) { List aList = new ArrayList(); aList.add("A"); aList.add("B"); aList.add("C"); aList.add("D"); aList.add("E"); System.out.println("The element C is available in ArrayList? " + aList.contains("C")); System.out.println("The element Z is available in ArrayList? " + aList.contains("Z")); } }
Output
The output of the above program is as follows
The element C is available in ArrayList? true The element Z is available in ArrayList? false
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. ArrayList.contains() is used to check if "C" and "Z" are available in the ArrayList and the result is displayed. A code snippet which demonstrates this is as follows
List aList = new ArrayList(); aList.add("A"); aList.add("B"); aList.add("C"); aList.add("D"); aList.add("E"); System.out.println("The element C is available in ArrayList? " + aList.contains("C")); System.out.println("The element Z is available in ArrayList? " + aList.contains("Z"));Advertisements
 