Java ArrayList.lastIndexOf() Method

 Posted On  | Yashwant Chavan 

In this tutorial you will learn about ArrayList.lastIndexOf() method. This method returns the index of the last occurrence of the specified element in this list. or -1 if this list does not contain the element.

syntax

Returns the index of the last occurrence of the specified element in this list. or -1 if this list does not contain the element.

int java.util.ArrayList.lastIndexOf(Object o)

Return

It returns the index of last occurrence of the specified element.

Java ArrayList.lastIndexOf() example

Refer below steps

  • Constructs an empty ArrayList with an initial capacity using new ArrayList<String>().
  • Add some elements in letters ArrayList using add() method. I have inserted some of duplicate elements in the ArrayList, It helps you to get the better idea how lastIndexOf() method works.
  • In first scenario, We will get the lastIndexOf() of letter P which returns the index position as 6.
  • In second scenario, We will get the lastIndexOf() of letter W which returns the index position as 5.
  • In last scenario, We will get the lastIndexOf() of letter Q which returns the index position as -1, because element is not present in ArrayList.
package com.technicalkeeda.app;

import java.util.ArrayList;

public class ArrayListLastIndexOf {
    public static void main(String[] args) {

        ArrayList <String> letters = new ArrayList <String> ();
        letters.add("R");
        letters.add("G");
        letters.add("W");
        letters.add("P");
        letters.add("B");
        letters.add("W");
        letters.add("P");
        letters.add("X");

        System.out.println("ArrayList.lastIndexOf():- " + letters.lastIndexOf("P"));
        System.out.println("ArrayList.lastIndexOf():- " + letters.lastIndexOf("W"));
        System.out.println("ArrayList.lastIndexOf():- " + letters.lastIndexOf("Q"));

    }
}

Output

ArrayList.lastIndexOf():- 6
ArrayList.lastIndexOf():- 5
ArrayList.lastIndexOf():- -1


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0329 seconds.