gpt4 book ai didi

Java ArrayList 日期变量排序?

转载 作者:行者123 更新时间:2023-11-30 04:13:32 30 4
gpt4 key购买 nike

我希望我的列表将根据 Date 进行排序变量,所以我必须编写这个逻辑

public  static void main(String a[]){
AuditLogComponent comp = new AuditLogComponent();
List<TableRecord> records = new ArrayList<TableRecord>();
LogFolderRecord log = new LogFolderRecord();
Date date = new Date();
Timestamp fromTS1 = new Timestamp(date.getTime());
log.setStampDate(fromTS1);
records.add(log);
Date date1 = new Date();
Timestamp fromTS2 = new Timestamp(date1.getTime());
LogFolderRecord log1 = new LogFolderRecord();
log1.setStampDate(fromTS2);
records.add(log1);
records.add(new LogPeopleRecord());

comp.columnsList(records);
}

以及我如何调用列表的排序方法

public void columnsList(List<TableRecord> records){

Collections.sort(records, new StampDateComparator());
for(TableRecord record : records){
Table table = record.getTable();
Field[] fields = table.fields();
for(Field field : fields){
field.getName();
record.getValue(field);

}
}

}

我的比较器类是

public class StampDateComparator implements Comparator<Object> {

@Override
public int compare(Object object1, Object object2) {

try {
Method method = object1.getClass().getDeclaredMethod("getStampDate");
Date value = (Date) method.invoke(object1);

Method method1 = object1.getClass().getDeclaredMethod("getStampDate");
Date value1 = (Date) method.invoke(object2);

if(value != null && value1 != null )
return value.compareTo(value1);;
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;

}

但它没有抛出异常

java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.csdcsystems.amanda.comp.macro.StampDateComparator.compare(StampDateComparator.java:22)
at java.util.TimSort.countRunAndMakeAscending(Unknown Source)
at java.util.TimSort.sort(Unknown Source)

根据日期进行排序的具体方法是什么?

最佳答案

您的 Comparator 类应如下所示

public class StampDateComparator implements Comparator<TableRecord> {

@Override
public int compare(TableRecord record1, TableRecord record2) {
return record1.getStampDate().compareTo(record2.getStampDate());
}
}

编辑:即使 TableRecord 是一个接口(interface),您仍然可以在 Compartor 中使用它,您的所有 TableRecord 实现都应该具有方法 getStampDate 已正确实现。

关于Java ArrayList 日期变量排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19001569/

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