ArrayList lastIndexOf() Method in Java

Published by user on

ArrayList lastIndexOf() is used when there are multiple elements in list with the same value and you want to find the highest index position of that value.

lastIndexOf() returns the largest index of the specified element from the ArrayList. If the specified element is not present then it returns -1.

The time complexity of this method is O(n).

Syntax:

public int lastIndexOf(Object o)

Parameters – o is the element to search.
Returns – The last index of the o if found otherwise returns -1.

Let’s have a look at the diagram.

ArrayList lastindexof

 

Program 1:

This program demonstrates the use of lastIndexOf(Object o) method.

import java.util.ArrayList;

// Demonstrates the use of 
// ArrayList lastIndexOf() method
public class ArrayListDemo {
	public static void main(String[] args) {
		// Create an ArrayList
		ArrayList<Integer> arrList = new ArrayList<>();
		arrList.add(11);
		arrList.add(17);
		arrList.add(33);
		arrList.add(17);
		arrList.add(11);
		// Now the List has element 17 twice
		System.out.println("ArrayList elements : " + arrList);
		// This call will find
		// the largest index of 17
		System.out.println("Last index of 17 is : " + arrList.lastIndexOf(17));
	}
}

Output:

ArrayList elements : [11, 17, 33, 17, 11]
Last index of 17 is : 3

Program 2:

The below program shows how it returns -1 if the element is not found in the list.

import java.util.ArrayList;

// Demonstrates how lastIndexOf()
// returns -1 when the
// specified element is not present
// in the list
public class ArrayListDemo {

	public static void main(String[] args) {
		// Create an ArrayList
		ArrayList<Integer> arrList = new ArrayList<>();
		arrList.add(100);
		arrList.add(200);
		arrList.add(300);
		arrList.add(400);
		arrList.add(500);

		System.out.println("ArrayList elements : " + arrList);
		// As 600 is not present
		// in the list then the
		// call to lastIndexOf returns -1
		System.out.println("Last index of 600 is : " + arrList.lastIndexOf(600));
	}
}

Output:

ArrayList elements : [100, 200, 300, 400, 500]
Last index of 600 is : -1

Further Reference:

ArrayList Documentation.

Categories: Java