Java中的 LinkedList lastIndexOf() 方法及示例
Java.util 包中存在的 LinkedList 类的lastIndexOf(Object element) 方法用于检查和查找列表中特定元素的出现。如果元素存在于列表中,则 lastIndexOf() 方法返回该元素最后一次出现的索引,否则返回 -1。此方法用于查找 LinkedList 中特定元素的最后一次出现。
句法:
LinkedList.lastIndexOf(Object element)
参数:参数元素的类型为 LinkedList。
It refers to the element whose last occurrence is required to be checked.
返回值:该元素在列表中最后出现的位置,否则如果该元素不在列表中,则该方法返回 -1。返回值是整数类型。
例子:
Java
// Java Program to Illustrate lastIndexOf() Method
// of LinkedList class
// Importing required classes
import java.io.*;
import java.util.LinkedList;
// Main class
public class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an empty LinkedList of string type
LinkedList list = new LinkedList();
// Adding elements in the list
// using add() method
list.add("Geeks");
list.add("for");
list.add("Geeks");
list.add("10");
list.add("20");
// Displaying the current elements inside LinkedList
System.out.println("LinkedList:" + list);
// The last position of an element is returned
// using lastIndexOf() method and
// displaying on the console
System.out.println(
"Last occurrence of Geeks is at index: "
+ list.lastIndexOf("Geeks"));
System.out.println(
"Last occurrence of 10 is at index: "
+ list.lastIndexOf("10"));
}
}
输出:
LinkedList:[Geeks, for, Geeks, 10, 20]
Last occurrence of Geeks is at index: 2
Last occurrence of 10 is at index: 3