如何在不使用内置函数的情况下排序n个日期?我能够使用内置代码执行操作。
java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat("dd-MM-yyyy");
String dates[] = { "05-11-2014" , "23-08-2014" , "05-02-2013" };
for ( String string : dates ) {
Date localdate=sdf.parse(string);
list.add( localdate );
}
Collections.sort( list );
这里,我想替换collections.sort()
函数
这里的例子,反向顺序比较器
class Comp implements Comparator< Date >
{
public int compare(Date o1, Date o2) {
return -( o1.compareTo( o2 ) ); //implement here order you want
}
}
public static void main( String[] args )
{
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String dates[] = { "05-11-2014" , "23-08-2014" , "05-02-2013" };
List< Date > list = new ArrayList< Date >();
for ( String string : dates ) {
try {
Date localdate = sdf.parse(string);
list.add( localdate );
} catch (ParseException e) {
e.printStackTrace();
}
}
Collections.sort( list );
System.out.println( list );
Collections.sort( list, new Comp() );
System.out.println( list );
}
结果[Tue Feb 05 00:00:00 CET 2013, Sat Aug 23 00:00:00 CEST 2014, Wed Nov 05 00:00:00 CET 2014]
[Wed Nov 05 00:00:00 CET 2014, Sat Aug 23 00:00:00 CEST 2014, Tue Feb 05 00:00:00 CET 2013]