java - Why the Output of Arrays.binarySearch(arr, "b") is -1. Please clarify
问题描述
import java.util.Arrays;
import java.util.Comparator;
public class MainClass {
public static void main(String args[]) {
String[] arr = { "c", "d", "b", "a", "e" };
InnerClass in = new InnerClass();
Arrays.sort(arr, in);
for (String str : arr) {
System.out.print(str + " ");
}
System.out.println(Arrays.binarySearch(arr, "b"));
}
static class InnerClass implements Comparator<String> {
public int compare(String s1, String s2) {
return s2.compareTo(s1);
}
}
}
Output e d c b a -1
for information if we replace Arrays.binarySearch(arr, "b") to Arrays.binarySearch(arr, "e") the output is Output e d c b a -6
解决方案
Your array isn't sorted.
binarySearch
only works on a sorted array:
The array must be sorted into ascending order according to the natural ordering of its elements (as by the sort(Object[]) method) prior to making this call. If it is not sorted, the results are undefined.
推荐阅读
- azure - Azure Function App V2 是否可以使用超过 1.5 Gb 的内存
- python - 在 python XA = B 中求解线性方程
- ansible - 在转义发送到 shell 命令的字符串时遇到问题
- java - 双链表java反向函数报错
- c++ - C++ 关于指针和使用函数将它们初始化到堆中的行为到底是什么?
- html - 在 RShiny 中访问 HTML 单选按钮值
- amazon-web-services - Linux (Ubuntu) 上的 CPU 使用率下降
- android - 带有阴影的半透明覆盖在 android 上添加了内部“阴影”
- python - Panda 添加到新数据集时将数据转换为 NaN
- regex - 全名的 HTML5 模式