java 排序 比较器

1. 专门为对象创建一个比较器,一般用匿名内部类来创建

2.排序对象中实现Comparable接口  通过其compareTo方法

public class GeRenInfo  implements Comparable<GeRenInfo>{

private Integer sxny;//所属年月

@Override
public String toString() {
return "sxny=" + sxny ;
}

public GeRenInfo() {
super();
// TODO Auto-generated constructor stub
}

public int getSxny() {
return sxny;
}
public void setSxny(int sxny) {
this.sxny = sxny;
}

public GeRenInfo(Integer sxny) {
super();
this.sxny = sxny;
}

@Override
public int compareTo(GeRenInfo o) {
int sxny01=this.sxny;
int sxny02=o.sxny;
int i=0;
if(sxny01> sxny02){
i=1;
}else if(sxny01<sxny02){
i=-1;
}
return i;

}

}

public class UnitShow {

@Test
public void unitShow() {
//比较器
Comparator comparator=new Comparator<GeRenInfo>() {
@Override
public int compare(GeRenInfo o1, GeRenInfo o2) {
int sxny01=o1.getSxny();
int sxny02=o2.getSxny();
int i=0;
if(sxny01> sxny02){
i=1;
}else if(sxny01<sxny02){
i=-1;
}
return i;
}
};
GeRenInfo[] gryf=new GeRenInfo[]{
new GeRenInfo(201407),
new GeRenInfo(201410),
new GeRenInfo(201406),
};
List<GeRenInfo>  list=new ArrayList<GeRenInfo>();
Collections.sort(list,comparator);//用比较器进行排序
System.out.println(list);
}

public class UnitShow {

@Test
public void unitShow() {
GeRenInfo[] gryf=new GeRenInfo[]{
new GeRenInfo(201407),
new GeRenInfo(201410),
new GeRenInfo(201406),
};
List<GeRenInfo>  list=new ArrayList<GeRenInfo>();
Collections.sort(list);//不用比较器
System.out.println(list);

}

©️2019 CSDN 皮肤主题: 创作都市 设计师: CSDN官方博客