排序中的比较器分为两种
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>();
list.add(new GeRenInfo(201407));
list.add(new GeRenInfo(201410));
list.add(new GeRenInfo(201406));
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>();
list.add(new GeRenInfo(201407));
list.add(new GeRenInfo(201410));
list.add(new GeRenInfo(201406));
Collections.sort(list);//不用比较器
System.out.println(list);
}
关于中文排序,官方给的排序并不是按首字母进行排序的:
待整理