📜  Java中的LinkedList indexOf()方法

📅  最后修改于: 2022-05-13 01:54:51.601000             🧑  作者: Mango

Java中的LinkedList indexOf()方法

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