我在下面的代码中遇到一个问题
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
变量(在每个类中)对它们进行排序,当列表中有不同的类时,我们如何进行排序?
发布于 2013-09-23 22:54:59
如果无法更改类,则编写比较器( 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);
}
}
}
发布于 2013-09-23 22:54:14
如果上面的代码是正确的,这意味着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);
}
}
发布于 2013-09-23 22:50:41
只需编写抽象类Record和受保护的字段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{
...
}
https://stackoverflow.com/questions/18974734
复制