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


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


java.util.AbstractList 類的 lastIndexOf() 方法用於返回此列表中指定元素的最後一次出現的索引,如果此列表不包含該元素,則返回 -1。更正式地說,返回滿足 (o==null ? get(i)==null:o.equals(get(i))) 的最高索引 i,如果沒有這樣的索引,則返回 -1。

用法:

public int lastIndexOf(Object o)

參數:此方法將 Object o 作為參數,該參數是要搜索的元素。

Returns Value:此方法返回此列表中指定元素最後一次出現的索引,如果此列表不包含該元素,則返回 -1。

異常:如果指定元素為 null 並且此列表不允許 null 元素,則此方法將引發 NullPointerException。



以下是說明 lastIndexOf() 方法的示例。

範例1:


// Java program to demonstrate
// lastIndexOf() method
// for String value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
        try {
  
            // Creating object of AbstractList<String>
            AbstractList<String>
                arrlist1 = new ArrayList<String>();
  
            // Populating arrlist1
            arrlist1.add("A");
            arrlist1.add("B");
            arrlist1.add("A");
            arrlist1.add("B");
            arrlist1.add("E");
  
            // print arrlist1
            System.out.println("ArrayList:"
                               + arrlist1);
  
            // getting the index of last occurrence
            // using lastIndexOf() method
            int lastindex = arrlist1.lastIndexOf("A");
  
            // printing the Index
            System.out.println("Last index of A:"
                               + lastindex);
        }
  
        catch (NullPointerException e) {
            System.out.println("Exception thrown:" + e);
        }
    }
}
輸出:
ArrayList:[A, B, A, B, E]
Last index of A:2

範例2:


// Java program to demonstrate
// lastIndexOf() method
// for NullPointerException
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // Creating object of AbstractList<String>
            AbstractList<String> arrlist1 = null;
  
            // print arrlist1
            System.out.println("ArrayList:"
                               + arrlist1);
  
            // getting the index of last occurrence
            // using lastIndexOf() method
            System.out.println("\nTrying to get"
                               + " the index from"
                               + " null ArrayList");
            int lastindex = arrlist1.lastIndexOf("B");
  
            // printing the Index
            System.out.println("Last index of B:"
                               + lastindex);
        }
  
        catch (NullPointerException e) {
            System.out.println("Exception thrown:" + e);
        }
    }
}
輸出:
ArrayList:null

Trying to get the index from null ArrayList
Exception thrown:java.lang.NullPointerException




相關用法


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