java - 简化自定义类型上 Collections.sort 的实现

标签 java generics sorting

我需要对我当前正在执行的工作列表进行排序:

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>>

是否可以避免传递比较器?

最佳答案

你可以这样做:

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

关于java - 简化自定义类型上 Collections.sort 的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14292571/

相关文章:

java - 打破 Completable Future 的 then apply 链

php - 如何公平地返回数据库结果-MySQL、PHP

c# - 没有 lambda 表达式的 Entity Framework 查询

javascript - Chrome Array.sorting 数字乱序

sql - 更改行的排序顺序后如何重新排列 "sort order"列

缺少 java.time::toString(String pattern) 方法

java - 如何监控媒体播放器接收的网络流量

java - 我的 AppCompatActivity 无法正常工作。为什么这样?

Swift 等效于 java 返回类型 : Class<? extends MyClass<?>>

java "generic generic type"