Java List lastIndexOf()方法及实例
此方法返回指定元素在此列表中出现的最后索引,如果此列表不包含该元素,则返回-1。
语法
int lastIndexOf(Object o)
参数: 该函数只有一个参数,即列表中要搜索的元素。
返回: 该方法返回列表中给定元素的最后出现的索引,如果元素不在列表中,则返回”-1″。
下面的程序显示了这个方法的实现。
程序1:
// Java code to show the implementation of
// lastIndexOf method in list interface
import java.util.*;
public class GfG {
// Driver code
public static void main(String[] args)
{
// Initializing a list of type Linkedlist
List<Integer> l = new LinkedList<>();
l.add(1);
l.add(3);
l.add(5);
l.add(7);
l.add(3);
System.out.println(l);
System.out.println(l.lastIndexOf(3));
}
}
输出:
[1, 3, 5, 7, 3]
4
程序2: 下面是使用Linkedlist实现list.lastIndexOf()的代码。
// Java code to show the implementation of
// lastIndexOf method in list interface
import java.util.*;
public class GfG {
// Driver code
public static void main(String[] args)
{
// Initializing a list of type Linkedlist
List<String> l = new LinkedList<>();
l.add("10");
l.add("30");
l.add("50");
l.add("70");
l.add("30");
System.out.println(l);
System.out.println(l.lastIndexOf("30"));
}
}
输出:
[10, 30, 50, 70, 30]
4
参考资料:
Oracle文档