解决方案 »
- JTextPane实现指定位置插入文字和图片
- 问个多线程Executors的小问题
- Java 数据类型的问题?????
- struts2 迭代问题 <s:property value="key" escape="false" />
- The Network Adapter could not establish the connection
- 爬山涉水翻遍贴子整理的JAVA入门书,排名没有先后
- 需要JBuilder 9的弟兄们,赶快到以下地址下载!速度还不错....
- 这段连接数据库的代码为什么会有SQLException异常?
- 我是新手,想请教个问题!!!
- 哪位高手帮我看一下下面代码,万分感谢!
- 新人求助关于线程同步问题。
- 虚拟机eclipse异常
字符串没办法比较大小,所以没办法定位吧
The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method) prior to making this call. If it is not sorted, the results are undefined.
如果用之前你没排序,结果就没有定义。
为什么我的代码如果是这样的话
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,我已经排序了
红色部分代码返回的是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));