Java 通过不同的方式订购集合

Java 通过不同的方式订购集合,java,compare,Java,Compare,我有这门课: public class Paint implements Comparable<Paint>{ private String cod_paint; private String title_paint; private String author; private int year; public Paint(String cod_paint,String title_paint,String author,int year){ th

我有这门课:

public class Paint implements Comparable<Paint>{

  private String cod_paint;
  private String title_paint;
  private String author;
  private int year;

  public Paint(String cod_paint,String title_paint,String author,int year){

    this.cod_paint = cod_paint;
    this.title_paint = title_paint;
    this.author = author;
    this.year = year;
  }

  /* And follow get method */

}

这样,当我在我的
ArrayList
上使用
sort
方法时,它将按
cod\u-paint
排序。但是现在我如何在相同的方法compareTo中实现另一种排序方式(按作者,按年份)?

如果需要不同的排序顺序,实现多个比较器()并将适当的比较器传递给函数更容易

这也可以使用匿名类在线完成:

Collections.sort(my_list, new Comparator<Paint>() {
  public int compare(Paint o1, Paint o2) { ... }
  boolean equals(Object obj) { ... }
});
Collections.sort(我的列表,新的比较器(){
公共整数比较(油漆o1,油漆o2){…}
布尔等于(对象对象对象){…}
});

不要使用
可比
,而是使用自定义的
比较器
。我将使用
Comparator
s的枚举:

public enum PaintComparator implements Comparator<Paint>{
    BY_NAME{
        @Override
        public int compareTo(Paint left, Paint right){
            return left.getAuthor().compareTo(right.getAuthor());
        }
    },
    // more similar items here
}
公共枚举PaintComparator实现Comparator{
名字{
@凌驾
公共内部比较(绘制左侧,绘制右侧){
返回left.getAuthor().compareTo(right.getAuthor());
}
},
//这里有更多类似的项目
}
现在按如下方式使用它:

List<Paint> myList = // init list here
Collections.sort(myList, PaintComparator.BY_NAME);
List myList=//此处初始化List
Collections.sort(myList,PaintComparator.BY_NAME);
见:

  • Java教程:

    • (+1)技术不错!这两个组件非常常见,但我从未见过它们以这种方式组合。但我必须将它们添加到我的类中,使其也具有可比性?@Mazzy否,除非您不使用自定义比较器。
      List<Paint> myList = // init list here
      Collections.sort(myList, PaintComparator.BY_NAME);