检查Java中的数组中是否存在值
首先对数组进行排序-
int intArr[] = {55, 20, 10, 60, 12, 90, 59}; //排序数组 Arrays.sort(intArr);
现在,在int变量中设置要搜索的值-
int searchVal = 12;
检查数组中是否存在值-
int retVal = Arrays.binarySearch(intArr,searchVal); boolean res = retVal > 0 ? true : false;
以下是检查数组中是否存在值的示例-
示例
import java.util.Arrays; public class Main { public static void main(String[] args) { //初始化未排序的int数组 int intArr[] = {55, 20, 10, 60, 12, 90, 59}; //排序数组 Arrays.sort(intArr); //让我们打印列表中所有可用的元素 System.out.println("排序的int数组是:"); for (int number : intArr) { System.out.println("Number = " + number); } //输入要搜索的值 int searchVal = 12; int retVal = Arrays.binarySearch(intArr,searchVal); boolean res = retVal > 0 ? true : false; System.out.println("Is element 12 in the array? = " + res); System.out.println("The index of element 12 is : " + retVal); } }
输出结果
排序的int数组是: Number = 10 Number = 12 Number = 20 Number = 55 Number = 59 Number = 60 Number = 90 Is element 12 in the array? = true The index of element 12 is : 1