Java Error(六)

Collection Sort 、binarySearch Warning :

import java.util.*;

public class ListInterface2 {
    public static void main(String []args){
        List L1 = new LinkedList();
        List L2 = new LinkedList();
        
        for(int i=0; i<=10; i++) {
            L2.add("b" + i);
        }
        
        for(int i=0; i<=9; i++) {
            L1.add("a" + i);
        }
        
        System.out.println(L2);
        System.out.println(L1);
        Collections.shuffle(L1);
        System.out.println(L1);
        Collections.reverse(L1);
        System.out.println(L1);
        Collections.sort(L1);
        System.out.println(L1);
        Collections.reverse(L1);
        Collections.copy(L2,L1);
        System.out.println(L2);
        System.out.println(L1);
        System.out.println(Collections.binarySearch(L1,"a3"));
    }
}

运行结果显示:

[b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10]
[a0, a1, a2, a3, a4, a5, a6, a7, a8, a9]
[a5, a1, a2, a9, a7, a8, a4, a6, a0, a3]
[a3, a0, a6, a4, a8, a7, a9, a2, a1, a5]
[a0, a1, a2, a3, a4, a5, a6, a7, a8, a9]
[a9, a8, a7, a6, a5, a4, a3, a2, a1, a0, b10]
[a9, a8, a7, a6, a5, a4, a3, a2, a1, a0]
-1
View Code

除去最后一项,结果与预期不同。其他一致。若要正确得出elem的index值,将代码进行如下修改。

import java.util.*;

public class ListInterface2 {
    public static void main(String []args){
        List L1 = new LinkedList();
        List L2 = new LinkedList();
        
        for(int i=0; i<=10; i++) {
            L2.add("b" + i);
        }
        
        for(int i=0; i<=9; i++) {
            L1.add("a" + i);
        }
        
        System.out.println(L2);
        System.out.println(L1);
        Collections.shuffle(L1);
        System.out.println(L1);
        Collections.reverse(L1);
        System.out.println(L1);
        Collections.sort(L1);
        System.out.println(L1);
        //Collections.reverse(L1);
        Collections.copy(L2,L1);
        System.out.println(L2);
        System.out.println(L1);
        System.out.println(Collections.binarySearch(L1,"a3"));
    }
}
[b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10]
[a0, a1, a2, a3, a4, a5, a6, a7, a8, a9]
[a5, a6, a1, a0, a9, a7, a8, a2, a4, a3]
[a3, a4, a2, a8, a7, a9, a0, a1, a6, a5]
[a0, a1, a2, a3, a4, a5, a6, a7, a8, a9]
[a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, b10]
[a0, a1, a2, a3, a4, a5, a6, a7, a8, a9]
3
View Code

出错原因,对List Interface 的中对象,进行查找,需要首先进行排序。查找基于排序 !

且只能用Collectin.Sort();  用Collection. reverse();会出现index为负数的情况。(具体原因,尚且未知,还请指点。:) )

参考部分回答:

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

参考于:https://zhidao.baidu.com/question/13681318.html  

个人理解,Sort()方法按正序排列,binarySearch才可以正常找到elem的index值,但是采用reverse(),会使binarySearch()找不到对应elem,故index值出错。但是具体内存分布和出现的原因,还请知道的人至指点。谢谢 :) 

原文地址:https://www.cnblogs.com/leafh/p/8732915.html