2016-05-06 22 views
1

假設我有以下對象類:排序名單的Android

public class Country { 
    private int ID; 
    private String name; 
    private Double distance; 
} 

,我有包含許多對象這個對象的列表:

List<Country> myList; 

我怎麼可以對列表進行排序基於Double distance,例如先放置距離較小的物體?有沒有現成的功能來做到這一點?

或者我想在另一個列表中存儲3個最小距離的國家。

回答

5

使用Collection.sort,並通過自己的實現Comparator

例:

List<Country> items = new ArrayList<Country>(); 

..... 
Collections.sort(items, new Comparator<Country>() { 

    @Override 
    public int compare(Country o1, Country o2) { 
     return Double.compare(o1.getDistance(), o2.getDistance()); 
    } 

}); 
+0

比較不需要是匿名的。也許最好把它改爲「你自己的」或類似的東西,以避免可能的誤解。 – Pshemo

+0

謝謝親愛的,問候。 @ΦXoce웃Пepeúpa – MSMC

+0

明白了......我將重新說明 –