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

本文介绍了一个Java排序的例子,通过实现Comparator接口来定义自定义排序规则。示例中使用Collections.sort方法对包含日期信息的对象列表进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[size=large][size=xx-large][color=darkblue][思想:排序的对象实现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][/color][/size][/size]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值