- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Get the index of a particular element in an ArrayList in Java
The index of a particular element in an ArrayList can be obtained by using the method java.util.ArrayList.indexOf(). This method returns the index of the first occurance of the element that is specified. If the element is not available in the ArrayList, then this method returns -1.
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("Orange"); aList.add("Apple"); aList.add("Peach"); aList.add("Guava"); aList.add("Mango"); System.out.println("The index of the element Apple in ArrayList is: " + aList.indexOf("Apple")); } }
Output
The output of the above program is as follows
The index of the element Apple in ArrayList is: 1
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. The method ArrayList.indexOf() is used to find the first index of element “Apple” and that is displayed. A code snippet which demonstrates this is as follows
List aList = new ArrayList(); aList.add("Orange"); aList.add("Apple"); aList.add("Peach"); aList.add("Guava"); aList.add("Mango"); System.out.println("The index of the element Apple in ArrayList is: " + aList.indexOf("Apple"));
- Related Articles
- Get the last index of a particular element in an ArrayList in Java
- Get the location of an element in Java ArrayList
- Add an element to specified index of ArrayList in Java
- How do you get the index of an element in a list in Java?
- Search an element of ArrayList in Java
- Get or set the element at the specified index in ArrayList in C#
- Get the size of an ArrayList in Java
- Check existence of an element in Java ArrayList
- Write a program to find the index of particular element in an array in javascript?
- Insert an element into the ArrayList at the specified index in C#
- Retrieve an element from ArrayList in Java
- How to replace an element of an ArrayList in Java?
- Replace an element in an ArrayList using the ListIterator in Java
- Obtain the Previous Index and Next Index in an ArrayList using the ListIterator in Java
- Remove an element from an ArrayList using the ListIterator in Java

Advertisements