2013-11-23 8 views
0

Я соорудив класс Пара:Отсортировать ArrayList комплексного типа

public class Couple<E,K> { 
    E first; K second; 

    Couple(E first, K second){ 
     this.first = first; 
     this.second = second; 
    } 
    public E getFirst(){ 
     return first; 
    } 
    public K getSecond(){ 
     return second; 
    } 
} 

И в ArrayList<Couple<String, Integer>>

ArrayList<Couple<URL, Integer>> a = ArrayList<Couple<URL, Integer>>(); 
a=fillArray(); 

Я хочу, чтобы отсортировать «а» значением второго элемента пары, что является целым числом.

+0

посмотрите: http://stackoverflow.com/questions/9708707/sorting-generic -arraylist-на-поле –

ответ

1

ли как этот

ваш SimpleComparator

class SimpleComparator implements Comparator<Couple<URL, Integer>> { 
    public int compare(Couple<URL, Integer> a, Couple<URL, Integer> b) { 
     return a.second.compareTo(b.second); 
    } 
} 

вашей сортировки

Collections.sort(a,new SimpleComparator()); // now a is sorted based on second value.  
0
a.sort(new Comparator<Couple<URL, Integer>>() { 
    public int compare(Couple<URL, Integer> a, Couple<URL, Integer> b) { 
     return a.second.compareTo(b.second); //assuming a.second is not null 
    } 
}); 
Смежные вопросы