Java如何查找数组中的特定元素或对象?
这个例子演示了如何在数组中查找特定的项。我们将使用org.apache.commons.lang.ArrayUtils类。这个类提供了一个名为contains(Object[] array,ObjectobjectToFind)的方法来检查数组中是否包含objectToFind对象。
还可以使用indexOf(Object[]array,ObjectobjectToFind)方法和lastIndexOf(Object[]array,ObjectobjectToFind)方法来获取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依赖
<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>