对ArrayList<T>中按照T的某个属性进行排序
1、先定义一个比较的方法
public class A implements Comparator<Object> {
public int compare(Object o1, Object o2) {
C c1=(C)o1;
C c2=(C)o2;
int flag=c1.getStuDate().compareTo(c2.getStuDate());
Log.i("MainActivity","----"+flag);
return flag;
}
}
2、书写数据源ArrayList<T>中实体类T
package com.xht.android.sortstime;
/**
* Created by Administrator on 2016-10-17.
*/
public class C {
private String stuDate;
private String stuName;
private String stuSex;
/**
* @return the stuName
*/
public String getStuName() {
return stuName;
}
/**
* @return the stuDate
*/
public String getStuDate() {
return stuDate;
}
/**
* @param stuDate the stuDate to set
*/
public void setStuDate(String stuDate) {
this.stuDate = stuDate;
}
/**
* @param stuName the stuName to set
*/
public void setStuName(String stuName) {
this.stuName = stuName;
}
/**
* @return the stuSex
*/
public String getStuSex() {
return stuSex;
}
/**
* @param stuSex the stuSex to set
*/
public void setStuSex(String stuSex) {
this.stuSex = stuSex;
}
}
3、主活动中获取数据源ArrayList<T>的数据,打印出原集合中的数据
//原集合中的数据
for(int i=0;i<list.size();i++){
C c=list.get(i);
Log.i(TAG, "--------;"+c.getStuDate()+" "+c.getStuName()+" "+c.getStuSex());
}
4、按照时间先后顺序对集合排序,并输出
//按时间先后排序后的数据 日期:前--->>后
Log.i(TAG, "--------;-----------");
A cm = new A();
Collections.sort(list,cm);
for(int i=0;i<list.size();i++){
C c=list.get(i);
Log.i(TAG, "--------;"+c.getStuDate()+" "+c.getStuName()+" "+c.getStuSex());
}
网友评论