📜  Java中的Java .util.Arraylist.indexOf()

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

Java中的Java .util.Arraylist.indexOf()

ArrayListindexOf()方法返回此列表中指定元素第一次出现的索引,如果此列表不包含该元素,则返回-1

句法 :

public int IndexOf(Object o)
obj : The element to search for.
// Java code to demonstrate the working of
// indexOf in ArrayList
  
// for ArrayList functions
import java.util.ArrayList;
  
public class IndexOfEx {
  public static void main(String[] args) {
       
  // creating an Empty Integer ArrayList
  ArrayList arr = new ArrayList(5);
  
  // using add() to initialize values
  arr.add(1);
  arr.add(2);
  arr.add(3);
  arr.add(4);
  
  // printing initial value
  System.out.print("The initial values in ArrayList are : ");
  for (Integer value : arr) {
  System.out.print(value);
  System.out.print(" ");
  }  
  
  // using indexOf() to find index of 3
  int pos =arr.indexOf(3);
    
  // prints 2
  System.out.println("\nThe element 3 is at index : " + pos);
  }
    
}   

输出:

The initial values in ArrayList are : 1 2 3 4 
The element 3 is at index : 2

实际应用:索引函数主要用于确定事件的最后一次或第一次出现,例如掷骰子中最后一次出现 6,或名称中任何字母第一次出现等。

再举一个例子:

// Java code to demonstrate the application of
// index functions in ArrayList
  
// for ArrayList functions
import java.util.ArrayList;
  
public class AppliIndex {
  public static void main(String[] args) {
       
  // creating an Empty Integer ArrayList
  ArrayList arr = new ArrayList(10);
  
  // using add() to initialize dice values
  arr.add(1);
  arr.add(2);
  arr.add(4);
  arr.add(6);
  arr.add(5);
  arr.add(2);
  arr.add(6);
  arr.add(1);
  arr.add(6);
  arr.add(4);
  
  // using IndexOf() to find first index of 6
  int pos1 =arr.indexOf(6);
    
  // using lastIndexOf() to find last index of 6
  int pos2 =arr.lastIndexOf(6);
    
  // to balance 0 based indexing
  pos1 = pos1+1;
  pos2 = pos2+1;
    
  // printing first index of 6
  System.out.println("The first occurrence of 6 is  : " + pos1);
    
  // printing last index of 6
  System.out.println("The last occurrence of 6 is  : " + pos2);
    
  }
    
}   

输出:

The first occurrence of 6 is  : 4
The last occurrence of 6 is  : 9