对ArrayList中的一个字符串属性排序

[size=xx-large][思想:排序的对象实现Comparator接口,实现compare方法;然后用Collections.sort(List list, Comparator c)排序就OK。

//排序实例
public int compare(PlainBean o1, PlainBean o2) {
if(o1.getRecordDate().compareTo(o2.getRecordDate())>0){
return 1;
}else if(o1.getRecordDate().compareTo(o2.getRecordDate())<0){
return -1;
}else {
return 0;
}
}

//要排序的对象:
public class PlainBean{

int userId;
double originalWeight;
double expected;
String startDate;
String endDate;
String recordDate;

public String getRecordDate() {
return recordDate;
}
public void setRecordDate(String recordDate) {
this.recordDate = recordDate;
}
…… //more get and set

//test
public static void main(String[] args) {
Test test = new Test();

List list = new ArrayList();
PlainBean p1 = new PlainBean();
p1.setRecordDate("2009-05-21");
PlainBean p2 = new PlainBean();
p2.setRecordDate("2009-05-22");
PlainBean p3 = new PlainBean();
p3.setRecordDate("2009-05-12");
list.add(p1);
list.add(p2);
list.add(p3);

Collections.sort(list, new MyComparator());//排序方法调用


      

for (int i = 0; i < 3; i++) {

PlainBean p=(PlainBean)list.get(i);
System.out.println(p.getRecordDate());



}

}
[/color]
[/size]

你可能感兴趣的:(C++,c,C#)