2014-01-30 83 views
0

我不知道如何爲Collectionos.binarySearch()寫比較器。誰能幫忙?示例代碼:二進制搜索比較器

List<Object> list1 = new ArrayList<>(); 

List<List<Object>> list2 = new ArrayList<>(); 


//loop starts 
// adds elements into list1 

list1.add(values); //值是含有如[3,約翰史密斯]

if (list2.size() == 0) { 
    list2.add(list1);//first element 
} else { 
    if (index >= 0) { 
    int index = Collections.binarySearch(list2, list1, comparator); 
    list2.add(index, list1);//I want to add these elements in ascending order ? 
} 
} 

//loop ends

元件如何編寫比較的對象,使得在列表中的元素2按升序或降序添加。

+0

這要看你怎麼想的列表進行排序?根據長度?內容的總和? ...? – Martin

+0

@Martin內容總和 –

+0

然後,你必須決定如何總結「3」,「John」和「Smith」,然後在Happy的答案中實現。 – Martin

回答

0

您可以實施IComparer<List<Object>> class或使用lambda表達式。

+0

我不記得具有ICompare類的java,你正在考慮C#。 Java有Comparable接口或比較器。 – Martin

1

你可以用它實現了一個Comparator<List<Object>>匿名類:

int index = Collections.binarySearch(list2, list1, new Comparator<List<Object>>() { 
    @Override 
    public int compare(List<Object> o1, List<Object> o2) { 
     // Your implementation here 
     return 0; 
    } 
}); 
0

你只需要創建一個實現Comparator接口的類。

例如,你可以這樣做內嵌匿名類:

Comparator<List<Object>> comparator = new Comparator<List<Object>>() { 

    @Override 
    public int compare(List<Object> x, List<Object> y) { 
     // custom logic to compare x and y here. Return a negative number 
     // if x < y, a positive number if x > y, and 0 otherwise 
    } 

}; 
Collections.binarySearch(list, comparator); 
+0

謝謝你。有效。 –