Java Java.util.Arraylist.indexOf()方法

Java Java.util.Arraylist.indexOf()方法

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

语法:

public int IndexOf(Object o)

obj : 要搜索的元素。

// 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<Integer> arr = new ArrayList<Integer>(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<Integer> arr = new ArrayList<Integer>(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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程