Java中AbstractSequentialList lastIndexOf()方法示例
java.util.AbstractSequentialList类的 lastIndexOf() 方法用于返回此列表中指定元素的第一个出现的索引,如果此列表不包含该元素,则返回-1。更正式地,返回最低的索引i,满足(o==null ? get(i)==null : o.equals(get(i))),如果没有这样的索引,则返回-1。
语法:
public int lastIndexOf(Object o)
参数:
此方法接受Object o作为参数,该参数是要搜索的元素。
返回值:
此方法返回此列表中指定元素的第一个出现的索引,如果此列表不包含该元素,则返回-1。
异常:
- ClassCastException:如果指定元素的类型与此列表不兼容。
- NullPointerException:如果指定元素为null,且此列表不允许null元素。
以下是演示 lastIndexOf() 方法的示例。
示例1:
// Java program to demonstrate lastIndexOf()
// method for AbstractSequentialList
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Creating object of AbstractSequentialList
AbstractSequentialList<Integer>
arrlist1 = new LinkedList<Integer>();
// Populating arrlist1
arrlist1.add(10);
arrlist1.add(20);
arrlist1.add(30);
arrlist1.add(40);
arrlist1.add(50);
// print arrlist1
System.out.println("AbstractSequentialList: "
+ arrlist1);
// getting the index of element 30
// using lastIndexOf() method
int index = arrlist1.lastIndexOf(30);
// print the index
System.out.println("Last Index of 30: "
+ index);
}
}
AbstractSequentialList: [10, 20, 30, 40, 50]
Last Index of 30: 2
示例2:
// Java program to demonstrate lastIndexOf()
// method for AbstractSequentialList
import java.util.*;
public class GFG1 {
public static void main(String[] args)
{
// Creating object of AbstractSequentialList
AbstractSequentialList<Integer>
arrlist1 = new LinkedList<Integer>();
// Populating arrlist1
arrlist1.add(10);
arrlist1.add(20);
arrlist1.add(30);
arrlist1.add(40);
arrlist1.add(50);
// print arrlist1
System.out.println("LinkedListlist: "
+ arrlist1);
// getting the index of element 100
// using lastIndexOf() method
int index = arrlist1.lastIndexOf(100);
// print the index
System.out.println("Last Index of 100: "
+ index);
}
}
LinkedListlist: [10, 20, 30, 40, 50]
Last Index of 100: -1
极客教程