【问题标题】:How to sort an ArrayList with 2 int parameters? [closed]如何使用 2 个 int 参数对 ArrayList 进行排序? [关闭]
【发布时间】:2015-03-18 02:39:03
【问题描述】:

我想对 Process 对象的数组列表进行排序。一个 Process 有 2 个参数:startTime 和 duration。我想在 startTime 中按升序对 arraylist 进行排序,对于相同的 startTime,我想在持续时间中按升序排序。我该怎么做?

【问题讨论】:

标签: java sorting arraylist


【解决方案1】:

首先,我假设您的 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&lt;Process&gt; 进行排序:

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&lt;Process&gt;,如下所示:

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.

【讨论】:

    【解决方案2】:

    您可以创建自定义Comparator

    或者您可以创建可重复使用的比较器来帮助处理未来的排序。例如,您可以使用Bean Comparator,它允许您对Process 对象的属性进行排序。该链接包含使用BeanComparator 或创建您自己的自定义Comparator 的示例代码。

    然后您可以使用Group Comparator,它允许您同时对多个属性进行排序。

    【讨论】:

      猜你喜欢
      • 2017-03-15
      • 2011-10-05
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多