我有这门课:
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 */
}
Run Code Online (Sandbox Code Playgroud)
现在我将创建一些对象Paint并将它们插入到集合中 ArrayList
之后我有这个集合一次排序author,另外一个时间year,一旦其他时间cod_paint.
要做到这一点,我必须在Paint中实现方法 compareTo
例如:
public int compareTo(Paint p){
return cod_paint.compareTo(p.cod_paint);
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式当我将使用我的方法时sort,ArrayList<Paint>它将被命令cod_paint.但是现在我怎样才能以相同的方法比较实现其他方式(按作者,按年)?
Sea*_*oyd 10
不要使用Comparable,Comparator而是使用自定义.我会用一个en Comparator:
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
}
Run Code Online (Sandbox Code Playgroud)
现在使用如下:
List<Paint> myList = // init list here
Collections.sort(myList, PaintComparator.BY_NAME);
Run Code Online (Sandbox Code Playgroud)
看到:
Comparator| 归档时间: |
|
| 查看次数: |
68 次 |
| 最近记录: |