ArrayList lastIndexOf() method in Java

The lastIndexOf() method helps find the last occurrence of a specified element within the ArrayList. This post will discuss the lastIndexOf() of the ArrayList class in detail.

We also have an indexOf() method in the ArrayList class, which is used to find the first occurrence of an element.

  • Method declaration – public int lastIndexOf(Object o)
  • What does it do? It will find the last occurrence of the specified element within the ArrayList, which means if the specified element is present multiple times, it will return the index of the last occurrence within the list. And the indexing is 0-based, which means if the element is found at the 4th position, then the function would return the index as 3
  • What does it return? It will return an integer indicating the last occurrence of the specified element, and if the element is not present in the ArrayList, then it will return -1
Code Example
public class Codekru {

	public static void main(String[] args) throws Exception {

		ArrayList<String> al = new ArrayList<String>();
		al.add("hi");
		al.add("codekru");
		al.add("hi");

		System.out.println(al.lastIndexOf("hi")); // this will return 2
		System.out.println(al.lastIndexOf("hello")); // this will return -1 as
														// "hello" is not present in the arraylist

	}
}

Output –

2
-1

Here, “hi” was present at two positions ( index 0 and index 2 ). As the lastIndexOf() method returns the last occurrence of the specified element, it returns 2 as the index. But it returned -1 for the element it couldn’t find in the ArrayList.

Internal implementation of the ArrayList lastIndexOf() method
    public int lastIndexOf(Object o) {
        return lastIndexOfRange(o, 0, size);
    }

    int lastIndexOfRange(Object o, int start, int end) {
        Object[] es = elementData;
        if (o == null) {
            for (int i = end - 1; i >= start; i--) {
                if (es[i] == null) {
                    return i;
                }
            }
        } else {
            for (int i = end - 1; i >= start; i--) {
                if (o.equals(es[i])) {
                    return i;
                }
            }
        }
        return -1;
    }

We can see that the lastIndexOf() method internally runs a for loop in reverse to find the last occurrence of the specified element in the ArrayList.

Time complexity of the ArrayList lastIndexOf() method
  • The best time complexity for the lastIndexOf() method would be O(1) when the element is found at the last position of the ArrayList itself
  • The worst-case scenario is when the specified element is not found in the ArrayList. Then its complexity would be O(n)
  • So, we can say that the average time complexity of the ArrayList lastIndexOf() method would be O(n)

The What If scenarios

What if we try to find the null object in an ArrayList containing null objects?

The lastIndexOf() method can also return the last occurrence of the null object if present in the ArrayList, as illustrated below.

public class Codekru {

	public static void main(String[] args) throws Exception {

		ArrayList<String> al = new ArrayList<String>();
		al.add(null);
		al.add("Hi");
		al.add("codekru");
		al.add(null);

		System.out.println("ArrayList contents: " + al);

		System.out.println("Last index of null object: " + al.lastIndexOf(null)); // this will return 2

	}
}

Output –

ArrayList contents: [null, Hi, codekru, null]
Last index of null object: 3
What if we use the lastIndexOf() on a null ArrayList?

In this case, it will throw NullPointerException.

public class Codekru {

	public static void main(String[] args) throws Exception {

		ArrayList<String> al = new ArrayList<String>();
		al = null;

		System.out.println(al.lastIndexOf("Hi"));

	}
}

Output –

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.ArrayList.lastIndexOf(Object)" because "al" is null

If we want the first occurrence of the specified element, then we can use the indexOf() method of the ArrayList class.

Please visit this link to learn more about the ArrayList class of java and its other functions or methods.

We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at admin@codekru.com.

Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *