实体类List排序实现(重写compareTo方法)
1,首先需要继承comparable接口并实现compareTo方法
public class Testentity implements Comparable<Testentity> {
//排序参数
private intsortScore;
public int getSortScore() {
return sortScore;
}
public void setSortScore(int sortScore) {
return this.sortScore = sortScore;
}
@Override
public int compareTo(Testentity o) {
//实现的是从大到小的排序 *倒序*
return (o.getSortScore())-this.getSortScore();
//实现的是从小到大的排序 *正序*
return this.getSortScore()-(o.getSortScore());
}
@Override
public String toString() {
return String.valueOf(this.getSortScore());
}
}
public class test{
public static void main(String[] args) {
Testentity t1 = new Testentity();
Testentity t2 = new Testentity();
Testentity t3 = new Testentity();
t1.setSortScore(10001);
t2.setSortScore(9923);
t3.setSortScore(12222);
List<Testentity> list = new ArrayList<Testentity>();
list.add(t1);
list.add(t2);
list.add(t3);
System.out.println("start:"+list.toString());
Collections.sort(list);
System.out.println("===========================================");
System.out.println("end:"+list.toString());
}
}
打印结果:
start:[10001, 9923, 12222]
===========================================
end[12222, 10001, 9923]
注意
遇到double类型的排序(问题不大不要慌,曲线救国)
根据double字段的位数来设置 排序参数
public class Testentity implements Comparable<Testentity> {
//排序参数
private int sortScore;
//排序数(double)
private double score;
public int getSortScore() {
return sortScore;
}
public double getScore() {
return score;
}
public void setScore(double score) {
//曲线救国来了,哈哈哈小数点后移
this.sortScore = (int) (score*100);
this.score = score;
}
@Override
public int compareTo(Testentity o) {
//实现的是从大到小的排序 *倒序*
return (o.getSortScore())-this.getSortScore();
//实现的是从小到大的排序 *正序*
return this.getSortScore()-(o.getSortScore());
}
@Override
public String toString() {
return String.valueOf(this.getSortScore());
}
}
public class test{
public static void main(String[] args) {
Testentity t1 = new Testentity();
Testentity t2 = new Testentity();
Testentity t3 = new Testentity();
t1.setScore(100.01);
t2.setScore(99.23);
t3.setScore(122.22);
List<Testentity> list = new ArrayList<Testentity>();
list.add(t1);
list.add(t2);
list.add(t3);
System.out.println("start:"+list.toString());
//排序
Collections.sort(list);
System.out.println("===========================================");
System.out.println("end:"+list.toString());
}
}
打印结果:
start:[10001, 9923, 12222]
===========================================
end[12222, 10001, 9923]
那么问题出现了
String类型呢?
Date类型呢?
还是 问题不大,不要慌!
String可以用compareTo方法去比较
date可以可以转成时间戳 哈哈哈哈
当然你也可以手动去编写一个比较的逻辑去返回对应的int
正序就是 this - 也就是返回正数
倒序就是 - this 也就是返回负数