[英]binarySearch with custom Comparator-object not checking first element
I am trying to make a custom Comparator-object to use with java.util.Arrays.binarySearch
. 我正在尝试使用
java.util.Arrays.binarySearch
创建自定义Comparator对象。
I want search the array for a String whose reverse value is equal to the reverse value of the target String element (dumb, I know, but it's just for learning). 我想在数组中搜索一个String,它的反向值等于目标String元素的反向值(哑,我知道,但它只是为了学习)。
However, when I attempt to run binarySearch
on the array, all the elements match properly, except array element 0. 但是,当我尝试在数组上运行
binarySearch
时,除了数组元素0之外,所有元素都正确匹配。
Comparator: 比较:
class SearchComparator<T extends Comparable<T>> implements Comparator<T> {
public int compare(T s1, T s2) {
String reverse1 = new StringBuilder((String)s1).reverse().toString();
String reverse2 = new StringBuilder((String)s2).reverse().toString();
return reverse1.equals(reverse2) ? 0 : -1;
}
}
Main function: 主功能:
String[] words = new String[]{"One", "Two", "Three", "Four"};
SearchComparator scmp = new SearchComparator();
System.out.println(Arrays.deepToString(words));
System.out.println(Arrays.binarySearch(words, "One", scmp));
System.out.println(Arrays.binarySearch(words, "Two", scmp));
System.out.println(Arrays.binarySearch(words, "Three", scmp));
System.out.println(Arrays.binarySearch(words, "Four", scmp));
Output: 输出:
[One, Two, Three, Four]
-5
1
2
3
What is up with -5
? 什么是
-5
? I don't know man. 我不认识男人。
The int compare(T s1, T s2)
from the Comparator<T>
interface returns a number that indicates whether s1
is less, equal to, or greater than s2
; 来自
Comparator<T>
接口的int compare(T s1, T s2)
返回一个数字,表示s1
是小于,等于还是大于s2
; your code compares s1
and s2
for equality, which is incorrect. 你的代码比较
s1
和s2
是否相等,这是不正确的。
You need to change the return
line of your code to call the method for lexicographic comparison of String
objects, like this: 您需要更改代码的
return
行以调用String
对象的字典比较方法,如下所示:
return reverse1.compareTo(reverse2);
Another problem is that your array is not sorted in accordance with the same comparator. 另一个问题是您的数组没有按照相同的比较器进行排序。 That is why you get negative indexes when you search in it.
这就是您在搜索时获得负索引的原因。 Add this line before making calls to
binarySearch
to fix the problem: 在调用
binarySearch
之前添加此行以解决问题:
Arrays.sort(words, scmp);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.