这个例子演示了如何在数组中查找特定的项。我们将使用org.apache.commons.lang.ArrayUtils类。这个类提供了一个名为contains(Object[]
array, Object objectToFind)的方法来检查数组中是否包含objectToFind对象。
还可以使用indexOf(Object[] array, Object objectToFind)方法和lastIndexOf(Object[] array, Object objectToFind)方法来获取objectToFind所在的数组元素的索引。package org.nhooo.example.commons.lang;
import org.apache.commons.lang3.ArrayUtils;
public class ArrayUtilsIndexOfDemo {
public static void main(String[] args) {
String[] colours = { "Red", "Orange", "Yellow", "Green",
"Blue", "Violet", "Orange", "Blue" };
// 颜色数组是否包含蓝色?
boolean contains = ArrayUtils.contains(colours, "Blue");
System.out.println("Contains Blue? " + contains);
// 您能告诉我以下定义的每种颜色的索引吗?
int indexOfYellow = ArrayUtils.indexOf(colours, "Yellow");
System.out.println("indexOfYellow = " + indexOfYellow);
int indexOfOrange = ArrayUtils.indexOf(colours, "Orange");
System.out.println("indexOfOrange = " + indexOfOrange);
int lastIndexOfOrange = ArrayUtils.lastIndexOf(colours, "Orange");
System.out.println("lastIndexOfOrange = " + lastIndexOfOrange);
}
}
这是上面代码的结果。Contains Blue? true
indexOfYellow = 2
indexOfOrange = 1
lastIndexOfOrange = 6
Maven依赖
org.apache.commons
commons-lang3
3.9