我正在尝试使用下面的代码按日期/时间(最新的优先)订购日期对象。顺序不正确。我认为该compareTo
方法需要以不同的方式实现以实现所需的排序?
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class DateSorter {
public static void main(String args[]){
List<DateObject> list = new ArrayList<DateObject>();
DateObject d1 = new DateObject("2012-12-05" , "11:21:19");
list.add(d1);
d1 = new DateObject("2012-12-05" , "11:20:19");
list.add(d1);
d1 = new DateObject("2012-12-05" , "11:20:19");
list.add(d1);
d1 = new DateObject("2012-12-04" , "10:20:19");
list.add(d1);
d1 = new DateObject("2010-12-07" , "13:20:19");
list.add(d1);
d1 = new DateObject("2012-12-05" , "11:20:19");
list.add(d1);
Collections.sort(list);
for(DateObject d : list){
System.out.println(d);
}
}
}
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateObject implements Comparable<Object> {
private String date;
private String time;
public DateObject(String date, String time) {
this.date = date;
this.time = time;
}
public int compareTo(Object o) {
DateFormat formatter;
Date date1 = null;
Date date2 = null;
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date1 = (Date) formatter.parse(this.date + " " + this.time);
date2 = (Date) formatter.parse(this.date + " " + this.time);
} catch (ParseException e) {
e.printStackTrace();
}
catch(NullPointerException npe){
System.out.println("Exception thrown "+npe.getMessage()+" date1 is "+date1+" date2 is "+date2);
}
return date1.compareTo(date2);
}
@Override
public String toString(){
return this.date+" "+this.time;
}
}
这是显示的输出:
2012-12-05 11:21:19
2012-12-05 11:20:19
2012-12-05 11:20:19
2012-12-04 10:20:19
2010-12-07 13:20:19
2012-12-05 11:20:19
这个输出应该是:
2010-12-07 13:20:19
2012-12-05 11:20:19
2012-12-05 11:20:19
2012-12-05 11:20:19
2012-12-05 11:21:19
2012-12-04 10:20:19
更新:当我将 compareTo 方法修改为:
public int compareTo(Object o) {
DateFormat formatter;
Date date1 = null;
Date date2 = null;
DateObject other = (DateObject) o;
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date1 = (Date) formatter.parse(this.date + " " + this.time);
date2 = (Date) formatter.parse(other.date + " " + other.time);
} catch (ParseException e) {
e.printStackTrace();
}
catch(NullPointerException npe){
System.out.println("Exception thrown "+npe.getMessage()+" date1 is "+date1+" date2 is "+date2);
}
return date1.compareTo(date2);
}
输出是:
2010-12-07 13:20:19
2012-12-04 10:20:19
2012-12-05 11:20:19
2012-12-05 11:20:19
2012-12-05 11:20:19
2012-12-05 11:21:19
这仍然不正确,因为 2012-12-05 应该出现在 2012-12-04 之前