當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Arraylist lastIndexOf()用法及代碼示例

Java中ArrayList的lastIndexOf()方法用於獲取ArrayList對象中最後一次出現的元素的索引。

用法:

lastIndexOf(element)

參數:要返回其最後一個索引的元素。


返回:
它返回參數中傳遞的元素的最後一次出現。如果找不到該元素,則返回-1。

演示lastIndexOf()工作原理的程序:

// Java code to demonstrate the working of 
// lastIndexOf() method in ArrayList 
  
// for ArrayList functions 
import java.util.ArrayList; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // creating an Empty Integer ArrayList 
        ArrayList<Integer> arr = new ArrayList<Integer>(7); 
  
        // using add() to initialize values 
        arr.add(10); 
        arr.add(20); 
        arr.add(30); 
        arr.add(40); 
        arr.add(30); 
        arr.add(30); 
        arr.add(40); 
  
        System.out.println("The list initially " + arr); 
  
        // last index of 30 
  
        int element = arr.lastIndexOf(30); 
        if (element != -1) 
            System.out.println("the lastIndexof of" +  
                             " 30 is " + element); 
        else
            System.out.println("30 is not present in" +  
                                        " the list"); 
  
        // last index of 100 
        element = arr.lastIndexOf(100); 
        if (element != -1) 
            System.out.println("the lastIndexof of 100" +  
                                      " is " + element); 
        else
            System.out.println("100 is not present in" +  
                                           " the list"); 
    } 
}

輸出:

The list initially [10, 20, 30, 40, 30, 30, 40]
the lastIndexof of 30 is 5
100 is not present in the list


相關用法


注:本文由純淨天空篩選整理自Striver大神的英文原創作品 Arraylist lastIndexOf() in Java with example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。