
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Get Last Index of Element in an ArrayList in Java
The last index of a particular element in an ArrayList can be obtained by using the method java.util.ArrayList.lastIndexOf(). This method returns the index of the last 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("Orange"); aList.add("Mango"); aList.add("Peach"); System.out.println("The last index of the element Orange in ArrayList is: " + aList.lastIndexOf("Orange")); } }
Output
The output of the above program is as follows
The last index of the element Orange in ArrayList is: 3
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.lastIndexOf() is used to find the last index of element “Orange” 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("Orange"); aList.add("Mango"); aList.add("Peach"); System.out.println("The last index of the element Orange in ArrayList is: " + aList.lastIndexOf("Orange"));
Advertisements