按日期排序需要做什么?

时间:2012-05-13 06:31:11

标签: java

我需要按日期对状态报告进行排序。在我调用addItem方法之前,应该完成排序,或者我必须按报告日期与之前的报告进行比较。需要说明的是,getReportDate()[类型为JVDate]方法可用于获取状态报告的报告日期。您能否帮助对状态报告进行排序:

   public void  doImport( TRDataReader in )
        throws IOException, TRException        
   {

       in.start( getClassTag() ); // get the class tag
       // import the set's flags from a datareader
       importFlags( in ); 
       beginLoad ();
       final String restag = new TRStatusReport().getClassTag ();
       while (in.nextToken (restag))  {
             addItem (new TRStatusReport (in));
       }
       endLoad ();
       in.end (getClassTag ());
   }

1 个答案:

答案 0 :(得分:2)

通过指定适当的比较器,只需使用Java的内置排序算法。喜欢以下内容:

public void  doImport(TRDataReader in) throws IOException, TRException {
    in.start(getClassTag()); // get the class tag
    importFlags(in); // import the set's flags from a datareader

    // Add the reports to a temporary list first.
    final String restag = new TRStatusReport().getClassTag();
    List<TRStatusReport> list = new ArrayList<TRStatusReport>();
    while (in.nextToken(restag)) {
        list.add(new TRStatusReport(in));
    }         

    // Now sort them.
    TRStatusReport[] array = list.toArray(new TRStatusReport[]{});
    Collections.sort(array, new Comparator<TRStatusReport>() {
        @Override
        public int compare(TRStatusReport o1, TRStatusReport o2) {
            return o1.getReportDate().compareTo(o2.getReportDate());
        }
    });

    // Add it to the internal list.
    beginLoad();
    for (int i = 0; i < array.length; i++) {
        addItem(array[i]);
    }
    endLoad();
    in.end( getClassTag() );
}

如果日期不是Java Date对象,则必须找到比较日期的方法。我盲目地编写了这段代码(我不知道对象是什么)并且有一些假设。例如,beginLoad()和endLoad()方法......是列表还是读取? ......如果是这样,可能需要将它们放在while子句中,然后加载对象并将其添加到临时列表中。