import java.util.*;public class TestCollections {
public static void main(String[] args) {
List l1 = new LinkedList();
for(int i=0; i<=9; i++) {
l1.add("a"+i);
}
System.out.println(l1);
Collections.shuffle(l1); // 随机输出
  System.out.println(l1);
  Collections.sort(l1); // 进行顺序排列
  System.out.println(l1);
  Collections.reverse(l1);  //逆序排列
  System.out.println(l1);
  System.out.println(Collections.binarySearch(l1,"a4")); // 二分法查找位置
}


}为什么最后输出a4的位置为-1   ,a9的位置为-11…… 

解决方案 »

  1.   

    如果搜索键包含在列表中,则返回搜索键的索引;否则返回 (-(插入点) - 1)。插入点 被定义为将键插入列表的那一点:即第一个大于此键的元素索引;如果列表中的所有元素都小于指定的键,则为 list.size()。注意,这保证了当且仅当此键被找到时,返回的值将 >= 0。 
    ====>也就是说,没有找到你的“a4”元素。注意,对象的比较
      

  2.   

    System.out.println(Collections.binarySearch(l1, "a9")); // 二分法查找位置
    System.out.println(l1);
    Collections.shuffle(l1); 
    System.out.println(Collections.binarySearch(l1, "a9")); // 二分法查找位置
    System.out.println(l1);// 随机输出
    Collections.sort(l1); // 进行顺序排列
    System.out.println(l1);
    System.out.println(Collections.binarySearch(l1, "a9")); // 二分法查找位置
    // Collections.reverse(l1); // 逆序排列
    System.out.println(Collections.binarySearch(l1, "a9")); // 二分法查找位置
    System.out.println(l1);
    System.out.println(Collections.binarySearch(l1, "a9")); // 二分法查找位置
    }
    }9
    [a0, a1, a2, a3, a4, a5, a6, a7, a8, a9]
    4
    [a5, a2, a0, a1, a9, a4, a6, a7, a8, a3]
    [a0, a1, a2, a3, a4, a5, a6, a7, a8, a9]
    9
    9
    [a0, a1, a2, a3, a4, a5, a6, a7, a8, a9]
    9
    =====》问题出在函数上。
      

  3.   

    使用二分搜索法搜索指定列表,以获得指定对象。在进行此调用之前,必须根据列表元素的自然顺序对列表进行升序排序(通过 sort(List) 方法)。如果没有对列表进行排序,则结果是不确定的。如果列表包含多个等于指定对象的元素,则无法保证找到的是哪一个。 =====>升序排序(通过 sort(List) 方法)。