当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。