首页 文章资讯内容详情

Java中的int lastIndexOf()函数

2026-06-04 1 花语

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

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

在这里,arr是int值的数组,而target是我们正在为其找到最后一个索引的int值。

我们首先来看一个例子-

示例

import com.google.common.primitives.Ints; class Demo { public static void main(String[] args) { int[] myArr = { 10, 20, 30, 40, 50, 60,20, 80, 20, 100 }; System.out.println(Ints.join("-", myArr)); //查找元素20的最后一个索引 int index = Ints.lastIndexOf(myArr, 20); if (index != -1) { System.out.println("元素 20 的最后一个索引 = " + index); } else { System.out.println("元素20不在数组中."); } } }

输出结果

10-20-30-40-50-60-20-80-20-100 元素 20 的最后一个索引 = 8