Java ArrayList lastIndexOf() Method
What is ArrayList ?
ArrayList provides us with dynamic arrays. The ArrayLists are resizable in nature , we can add or remove an element at anytime. It is not compulsory to mention size while declaring it. The ArrayList is a part of Java framework and can be found in the java.util pacakge. ArrayList have many inbuilt methods which we can use. One of them is Java ArrayList lastIndexOf() Method.
Here on this page we will discuss about ArrayList lastIndexOf() method.
Java ArrayList lastIndexOf() Method
The lastIndexOf() method can be found in java.util.ArrayList package. This method is used to find the last occurrence of the element in the arraylist. If the element is not present in the list it return -1. It’s syntax, parameters, return values are discussed below with examples.
Syntax :
ArrayList.lastIndexOf(object);
Parameters :
ArrayList: name of the list. object: the element whose last index is to be returned.
lastIndexOf() return values :
1. Return the last index of the element if it is present in the list. 2. Return -1 if the element is not present in the list.
ArrayList lastIndexOf() Method Examples:
Example :
import java.util.ArrayList; class Main { public static void main (String[]args) { // creating an String ArrayList ArrayList < Integer > list = new ArrayList <> (); // adding elements to the list list.add (1); list.add (4); list.add (3); list.add (4); list.add (8); list.add (4); list.add (9); // check the last index of 4 int result = list.lastIndexOf (4); System.out.println ("Last index of 4 is " + result); // check the last index of 7 result = list.lastIndexOf (7); System.out.println ("Last index of 7 is " + result); } }
Output :
Last index of 4 is : 5 Last index of 7 is : -1
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment