Java如何搜索数组中的特定值?
package org.nhooo.example.util;
import java.util.Arrays;
public class ArraySearchExample {
public static void main(String[] args) {
//我们创建一个将要进行搜索的整数数组。
int items[] = {9, 5, 14, 6, 11, 28, 9, 16, 37, 3, 2};
//Arrays.binarySearch()要求我们对数组进行排序
//项目,然后再调用该方法。我们可以利用
//Arrays.sort()方法可以做到这一点。如果我们不对
//数组结果将是不确定的,搜索过程
//将返回否定结果。
Arrays.sort(items);
//要搜索,我们使用Arrays.binarySearch()方法,该方法接受
//任何数组类型的参数。为了搜索,我们传递了数组
//要搜索的内容和要搜索的密钥。
//
//当搜索项在数组中存在多个时,这
//方法不能保证将返回哪一个。
int needle = 9;
int index = Arrays.binarySearch(items, needle);
//打印出9号在数组中的位置。
System.out.println("Items: " + Arrays.toString(items));
System.out.println("Item " + needle + " is at index " + index);
}
}代码段的结果是:
Items: [2, 3, 5, 6, 9, 9, 11, 14, 16, 28, 37] Item 9 is at index 5
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短