2013-11-23 95 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(); 

我想排序「A」由夫婦的第二個元素的值是一個整數。

+0

看一看:http://stackoverflow.com/questions/9708707/sorting-generic -arraylist-ON-A-場 –

回答

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 
    } 
});