gpt4 book ai didi

Java ArrayList 基于动态对象字段进行排序?

转载 作者:行者123 更新时间:2023-12-01 18:43:24 29 4
gpt4 key购买 nike

我遇到一个问题,代码如下

public void columnsList(List<TableRecord> records){

for(TableRecord record : records){
Table table = record.getTable();
//Do sort here on stampDate
Field[] fields = table.fields();
for(Field field : fields){
field.getName();
record.getValue(field);

}
}

}

records对象包含不同类类型的对象

List<TableRecord> records = new List<TableRecord>();
records.add(new AddressRecord());
records.add(new CityRecord());
records.add(new UserRecord());

现在我需要如何通过每个类中的 stampDate 变量对它们进行排序,当列表中有不同的类时我们该怎么做

最佳答案

如果上面的代码正确,则意味着 AddressRecordCityRecordUserRecord 都扩展了 TableRecord:

class AddressRecord extends TableRecord {
// other fields and methods here
}
class CityRecord extends TableRecord {
// other fields and methods here
}
class UserRecord extends TableRecord {
// other fields and methods here
}

您只需为此类编写一个Comparator。它应该看起来像这样:

class TableRecord {
private Date timeStamp;

public Date getTimeStamp() {
return timeStamp;
}
// other fields and methods here
}

class RecordStampDateComparator implements Comparator<TableRecord>{

public int compare(TableRecord tr1, TableRecord tr2) {
Date tr1Date = tr1.getTimeStamp();
Date tr2Date = tr2.getTimeStamp();
return tr1Date.compareTo(tr2Date);
}
}

关于Java ArrayList 基于动态对象字段进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18974734/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com