Java中的LinkedList indexOf()函数
Java.util.LinkedList.indexOf(Object element)函数用于检查并找到列表中特定元素的出现次数。如果元素存在,则返回元素第一次出现的位置,否则返回-1。
语法:
LinkedList.indexOf(Object element)
参数: 参数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<String> list = new LinkedList<String>();
// 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
极客教程