1.pojo
package pojo;
public class Mybean implements java.io.Serializable {
private int id;
private String time;
public Mybean(int id, String time){
this.id = id;
this.time = time;
}
//get()、set()方法
}
2. 比较器
package pojo;
import java.util.Comparator;
public class MyComparator implements Comparator {
public int compare(Object arg0, Object arg1) {
Mybean info0=(Mybean)arg0;
Mybean info1=(Mybean)arg1;
Integer time0 = Integer.parseInt( info0.getTime() );
Integer time1 = Integer.parseInt( info1.getTime() );
int flag = time0.compareTo( time1 );
if( flag == 0){
return new Integer( info0.getId() )
.compareTo(new Integer( info1.getId() ));
}
return flag;
}
}
3.应用
//测试类
public class SortTest {
public static void main(String[] args){
List beans=new ArrayList();
beans.add(new Mybean(1,"45783"));
beans.add(new Mybean(4,"1573568"));
beans.add(new Mybean(6,"53573"));
beans.add(new Mybean(8,"253737"));
beans.add(new Mybean(9,"5573"));
beans.add(new Mybean(5,"5573"));
beans.add(new Mybean(9,"65737"));
MyComparatorcomparator=new MyComparator();
Collections.sort(beans, comparator);
for (int i = 0; i < beans.size(); i++){
Mybean bean = (Mybean )beans.get(i);
System.out.println(bean.getId()+"," + bean.getTime());
}
}
}
转载于:https://blog.51cto.com/moonght/1279180