📜  Java中的 AbstractList lastIndexOf() 方法及示例

📅  最后修改于: 2022-05-13 01:55:22.785000             🧑  作者: Mango

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作为参数,该参数是要搜索的元素。

返回值:此方法返回此列表中指定元素的最后一次出现的索引,如果此列表不包含该元素,则返回 -1。

异常:如果指定元素为空且此列表不允许空元素,则此方法抛出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
            AbstractList
                arrlist1 = new ArrayList();
  
            // 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
            AbstractList 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