Java ArrayList lastIndexOf() Method

Java ArrayList Java ArrayList

The lastIndexOf() method returns the position of the last occurrence of the specified element in the dynamic array.

The syntax of the lastIndexOf() method is:

arraylist.lastIndexOf(Object obj)

Note:arraylist is an object of the ArrayList class.

Parameter Description:

  • obj - the element to search for

Return Value

Returns the index value of the last occurrence of the specified element in the dynamic array.

If the obj element appears repeatedly in the dynamic array, the index value of the last occurrence of obj in the array is returned.

If the specified element does not exist in the dynamic array, the lastIndexOf() method returns -1.

Example

Get the index value of the last occurrence of an ArrayList element:

Example

import java.util.ArrayList;

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

        // create an array
        ArrayList<String> sites = new ArrayList<>();

        sites.add("Google");
        sites.add("Example");
        sites.add("Taobao");
        sites.add("Example");
        System.out.println("Website list: " + sites);


        // get the last occurrence position of Example
        int position1 = sites.lastIndexOf("Example");
        System.out.println("Last occurrence position of Example: " + position1);

        // Wiki is not in arraylist
        // returns -1
        int position2 = sites.lastIndexOf("Wiki");
        System.out.println("Last occurrence position of Wiki: " + position2);
    }
}

Executing the above program produces the following output:

网站列表: [Google, Example, Taobao, Example]
Example 最后出现的位置: 3
Wiki 最后出现的位置: -1

In the above example, we created a dynamic array named sites.

Note these expressions:

// 返回 3
sites.lastIndexOf("Example");

// Wiki 不在动态数组中,返回 -1
sites.lastIndexOf("Wiki");

The lastIndexOf() method successfully returned the position of the last occurrence of Example (i.e., 3). The element Wiki does not exist in the arraylist. Therefore, the method returns -1.

If we want to get the index value of the first occurrence of Example, we can use the indexOf() method. To learn more, visitJava ArrayList indexOf() 。

Note:We can also useJava ArrayList get()method to get the element at the specified index position.

Java ArrayList Java ArrayList

Other extensions