我在代码下面遇到了一个问题
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
对象包含不同类类型的Object
List<TableRecord> records = new List<TableRecord>();
records.add(new AddressRecord());
records.add(new CityRecord());
records.add(new UserRecord());
现在我需要按每个类中的stampDate
变量对它们进行排序当我们在列表中有不同的类时,我们怎么能这样做
答案 0 :(得分:2)
如果您的上述代码正确无误,则表示AddressRecord
,CityRecord
和UserRecord
都延伸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);
}
}
答案 1 :(得分:1)
只需使用受保护字段 stampDate 编写抽象类记录,即实现可比较并覆盖 compareTo 方法。
public abstract class Record implements Comparable<Record> {
protected Date stampDate;
@Override
public int compareTo(Record anotherRecord){
return this.stampDate.compareTo(anotherRecord.stampDate);
}
}
然后使用您的记录类扩展此类:
public class AddressRecord extends Record{
...
}
public class CityRecord extends Record{
...
}
public class UserRecord extends Record{
...
}
答案 2 :(得分:1)
如果您无法更改类,请编写比较器(Comparator<Object>
),这将尝试查找字段stampDate并进行比较。比用它来排序列表。
比较器实现:
import java.util.Comparator;
import java.util.Date;
public class StampDateComparator implements Comparator<Object> {
@Override
public int compare(Object o1, Object o2) {
try {
Date d1 = (Date) o1.getClass().getDeclaredField("stampDate").get(o1);
Date d2 = (Date) o2.getClass().getDeclaredField("stampDate").get(o2);
return compare(d1, d2);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchFieldException e) {
throw new RuntimeException("Missing variable stampDate");
}catch (ClassCastException e) {
throw new RuntimeException("stampDate is not a Date");
} catch (IllegalArgumentException e) {
//shoud not happen
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
答案 3 :(得分:0)
在List上使用以下Comparator类。
class TableRecordCompare implements Comparator<TableRecord>{
if(TableRecord instanceof AddressRecord){
// return compareTo for sample data of address.
}
else if(TableRecord instanceof CityRecord){
// return compareTo for sample data of CityRecord.
}
else{
// return compareTo for sample data of UserRecord.
}
}