標籤:alt binary AC rgs 指定 出錯 span sort ring
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值出錯。但是具體記憶體分布和出現的原因,還請知道的人至指點。謝謝 :)
Java Error(六)