日期:2014-05-20  浏览次数:20640 次

关于Collections.binarySearch
Java code

List<String> list3 = new ArrayList<String>();
list3.add("o");
list3.add("m");
list3.add("k");
System.out.println(Collections.binarySearch(list3, "k"));


怎么会输出-1呢。。。。。不应该是2吗

Java code

List<String> list3 = new ArrayList<String>();
list3.add("o");
list3.add("m");
list3.add("k");
list3.add("d");
list3.add("e");
list3.add("f");
list3.add("g");
list3.add("h");
list3.add("i");
System.out.println(Collections.binarySearch(list3, "d"));
System.out.println(Collections.binarySearch(list3, "e"));


这时候e对了,d还是错的,什么情况,求解释

------解决方案--------------------
Searches the specified list for the specified object using the binary search algorithm. 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. If the list contains multiple elements equal to the specified object, there is no guarantee which one will be found.