Java中的int indexOf()函数

Ints类的indexOf()方法返回数组中值目标首次出现的索引。语法如下-

public static int indexOf(int[] arr, int target)

在这里,参数arr是一个int值的数组,而target是要检查的首次出现的值。

现在让我们看一个例子-

示例

import com.google.common.primitives.Ints;
class Demo {
   public static void main(String[] args) {
      int[] arr = { 10, 20, 30, 40, 50, 60,70, 80, 90, 100 };
      int index = Ints.indexOf(arr, 40);
      if (index != -1) {
         System.out.println("Element 40 is in the array at position " + (index+1));
      } else {
         System.out.println("Element 40 is not in the array");
      }
   }
}

输出结果

Element 40 is in the array at position 4