Java.util.LinkedList.indexOf(Object element)方法用于检查和查找列表中特定元素的出现。如果元素存在,则返回元素第一次出现的索引,否则如果列表不包含该元素,则返回-1。
句法:
LinkedList.indexOf(Object element)
参数:参数元素的类型为LinkedList。它指定需要在LinkedList中检查其出现的元素。
返回值:如果列表中不存在该元素,则该方法返回列表中元素第一次出现的索引或位置,否则返回-1 。返回值为整数类型。
下面的程序说明了Java.util.LinkedList.indexOf()方法:
// Java code to illustrate indexOf()
import java.io.*;
import java.util.LinkedList;
public class LinkedListDemo {
public static void main(String args[]) {
// Creating an empty LinkedList
LinkedList list = new LinkedList();
// Use add() method to add elements in the list
list.add("Geeks");
list.add("for");
list.add("Geeks");
list.add("10");
list.add("20");
// Displaying the list
System.out.println("LinkedList:" + list);
// The first position of an element
// is returned
System.out.println("The first occurrence of Geeks is at index:"
+ list.indexOf("Geeks"));
System.out.println("The first occurrence of 10 is at index: "
+ list.indexOf("10"));
}
}
输出:
LinkedList:[Geeks, for, Geeks, 10, 20]
The first occurrence of Geeks is at index: 0
The first occurrence of 10 is at index: 3