首先,我假设您的 Process 类看起来像这样(加上其他内容):
public class Process{
private int startTime;
private int duration;
public int getStartTime(){
return startTime;
}
public int getDuration(){
return duration;
}
}
第一种选择,Processes的“默认”排序方法是按照你说的方法(先startTime升序,然后是duration升序),你可以让Process实现Comparable<Process>:
public class Process implements Comparable<Process>{
private int startTime;
private int duration;
public int compareTo(Process other){
if(startTime < other.startTime) return -1;
if(startTime > other.startTime) return 1;
//If here, startTime == other.startTime
if(duration < other.duration) return -1;
if(duration > other.duration) return 1;
return 0;
}
}
然后您可以使用简单的方法对ArrayList<Process> 进行排序:
ArrayList<Process> a = new ArrayList<Process>();
//Fill up a with process instances
Collections.sort(a); //Sorts according to the compareTo method in Process.
但是,如果这不是对流程进行排序的默认方法,(或者您无法使流程实现 Comparable,那么您将需要定义一个自定义 Comparator<Process>,如下所示:
class ProcessComparator implements Comparator<Process>{
public int compare(Process p1, Process p2){
if(p1.getStartTime() < p2.getStartTime()) return -1;
if(p1.getStartTime() > p2.getStartTime()) return 1;
//If here, p1.startTime == other.startTime
if(p1.getDuration() < p2.getDuration()) return -1;
if(p1.getDuration() > p2.getDuration()) return 1;
return 0;
}
}
然后,像这样使用一个:
ArrayList<Process> a = new ArrayList<Process>();
//Fill up a with process instances
Collections.sort(a, new ProcessComparator()); //Sorts according to the compareTo method in Process.