- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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"));
- Related Articles
- How to check existence of an element in android listview?
- Search an element of ArrayList in Java
- How to replace an element of an ArrayList in Java?
- Retrieve an element from ArrayList in Java
- Get the location of an element in Java ArrayList
- Add an element to specified index of ArrayList in Java
- Check whether an element is contained in the ArrayList in C#
- How to remove an element from ArrayList in Java?
- Replace an element in an ArrayList using the ListIterator in Java
- Remove an element from an ArrayList using the ListIterator in Java
- Get the index of a particular element in an ArrayList in Java
- How do you search for an element in an ArrayList in Java?
- Check for the existence of a key in Java IdentityHashMap
- Check for the existence of a value in Java IdentityHashMap
- How to check if ArrayList contains an item in Java?

Advertisements