u123
u123

Reputation: 16287

Simplify implementation of Collections.sort on custom type

I need to sort a List of Job which I currently do with:

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

where:

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

I would like to simplify this. So I have tried:

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

and

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

But get:

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

Is it possible to avoid passing a Comparator?

Upvotes: 0

Views: 105

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382142

You could do it like this :

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

Upvotes: 3

Related Questions