一个关于Collections类的问题,求解决!!
import java.util.*;
public class TestCollections {
public static void main(String[] args) {
List<String> list = Arrays.asList("red","green","blue");
System.out.println(Collections.binarySearch(list,"red"));
List<Integer> list1 = Arrays.asList(2,4,7,10,11,45,50,59,60,66);
System.out.println(Collections.binarySearch(list1,2));
}
}
运行这个代码后,输出结果为
-4
0
为什么会输出-4,不是0吗??
------解决方案-------------------- 引用: 但是我又有个问题了
为什么我的代码如果是这样的话
import java.util.*;
public class TestCollections {
public static void main(String[] args) {
List<String> list = Arrays.asList("red","green","blue");
Collections.sort(list);
Collections.sort(list);
System.out.println(list);
Collections.sort(list,Collections.reverseOrder());
System.out.println(list);
System.out.println(Collections.binarySearch(list,"red"));
List<Integer> list1 = Arrays.asList(2,4,7,10,11,45,50,59,60,66);
System.out.println(Collections.binarySearch(list1,2));
}
}
就输出
[blue, green, red]
[red, green, blue]
-4
0
为什么还是-4,我已经排序了
Collections.sort(list,
Collections.reverseOrder() );
红色部分代码返回的是Comparator<T>比较器
Comparator c=Collections.reverseOrder();
可是你比较的时候却没有传入这个比较器,仍然调用的是:
System.out.println(Collections.binarySearch(list,"red",));
就是这个方法:
binarySearch(List<? extends Comparable<? super T>> list, T key)
所以自然就对不上了,binarySearch有个重载的方法,有比较器参数,你调用这个就对了:
binarySearch(List<? extends T> list, T key, Comparator<? super T> c)
所以你代码改成这样就好了:
List<String> list = Arrays.asList("red","green","blue");
Collections.sort(list);
Collections.sort(list);
System.out.println(list);
Collections.sort(list,Collections.reverseOrder());
System.out.println(list);
System.out.println(Collections.binarySearch(list,"red",Collections.reverseOrder()));
List<Integer> list1 = Arrays.asList(2,4,7,10,11,45,50,59,60,66);
System.out.println(Collections.binarySearch(list1,2));