2013-01-12 224 views
0

簡化實施Collections.sort我需要梳理工作的名單,我現在做的:自定義類型

List<Job> jobs = new ArrayList<Job>(); 
Job job0 = new Job("a", 1, Arrays.asList("t0")); 
Job job1 = new Job("a", 2, Arrays.asList("t0")); 
jobs.add(job0); 
jobs.add(job1); 
Comparator<Job> comparator = new Comparator<Job>() { 
    @Override 
    public int compare(Job o1, Job o2) { 
    if (o1.getOrder() > o2.getOrder()) { 
     return 1; 
    } 
    return 0; 
    } 
}; 
Collections.sort(jobs, comparator); 

其中:

public class Job { 
    private String path; 
    private List<String> targets; 
    private final int order; 
    public Job(String path, int order, List<String> targets) { 
    this.path = path; 
    this.order = order; 
    this.targets = targets; 
    } 
... 
    public int getOrder() { 
    return order; 
    } 
} 

我想對此進行簡化。所以,我曾嘗試:

public class Job implements Comparable<Integer> { 
    private String path; 
    private List<String> targets; 
    private final int order; 
    public Job(String path, int order, List<String> targets) { 
    this.path = path; 
    this.order = order; 
    this.targets = targets; 
    } 
    public int compareTo(Integer o) { 
    // TODO Auto-generated method stub 
    return 0; 
    } 
} 

List<Job> jobs = new ArrayList<Job>(); 
Collections.sort(jobs); 

但得到:

Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (List<Job>). The inferred type Job is not a valid substitute for the bounded parameter <T extends Comparable<? super T>> 

是否有可能避免將一個比較?

+2

你需要'Job'實現可比''(你爲什麼要把它實現可比''?)。 – fge

+1

這是a.compareTo(b)= -b.compareTo(a)的要求,您必須在相反的情況下返回-1,當您返回+1時,反之亦然。 –

+0

@PeterLawrey如果你失敗會發生什麼?只是一個破碎的排序順序? –

回答

3

你可以做這樣的:

public class Job implements Comparable<Job> { // a job is comparable to another job 
    private String path; 
    private List<String> targets; 
    private final int order; 
    public Job(String path, int order, List<String> targets) { 
    this.path = path; 
    this.order = order; 
    this.targets = targets; 
    } 
    public int compareTo(Job j) { 
    return this.order - j.order; // here you specify how you want your jobs sorted 
    } 
} 
+3

這是受整數溢出(OK,不太可能),你可以使用'Integer.compare()'代替。 – fge

+0

它更安全地使用像this.order> that.order? 1:(this.order radai

+1

@radai只需使用'Integer.compare(order,j.order)'(不需要'this'限定符)對你來說 – fge