public class TestArray {
public static void main(String[] args) {
String[] colors = {"blue", "green", "yellow", "gray", "black", "red", "white"};
Arrays.sort(colors);
System.out.println(Arrays.toString(colors));
//[black, blue, gray, green, red, white, yellow]
int index1 = Arrays.binarySearch(colors, "red");
int index2 = Arrays.binarySearch(colors, "orange");
System.out.println("index1=====" + index1 + "=====index2===" + index2);
//index1=====4=====index2===-5
}
}
输出结果为:
4 -5
orange 在 colors数组中不存在,一直很纳闷为什么index2会等于 -5
查看JDK API 才知道:
binarySearch
public static int binarySearch(byte[] a,
byte key)
使用二分搜索法来搜索指定的 byte 型数组,以获得指定的值。必须在进行此调用之前对数组进行排序(通过 sort(byte[]) 方法)。如果没有对数组进行排序,则结果是不确定的。如果数组包含多个带有指定值的元素,则无法保证找到的是哪一个。
-
-
参数:
-
a- 要搜索的数组key- 要搜索的值
返回:
- 如果它包含在数组中,则返回搜索键的索引; 否则返回 (-(插入点) - 1)。 插入点 被定义为将键插入数组的那一点:即第一个大于此键的元素索引,如果数组中的所有元素都小于指定的键,则为 a.length。注意,这保证了当且仅当此键被找到时,返回的值将 >= 0。
当找不到要搜索的值时,返回 (-(插入点) - 1) 找到插入的位置的索引
例子中的 orange 插入点的索引是 4 所以 输出的是 -4-1 = -5
-
本文详细解析了Java中如何使用二分查找方法(binarySearch)定位数组中的元素位置,包括查找成功时返回的索引值及查找失败时返回的特殊值含义。
605

被折叠的 条评论
为什么被折叠?



