2011-12-23 76 views

回答

3

這可以在完成兩種常見的方式。

有學生提供的可比的實現,最終將按照日期最簡單的辦法

1)。這是一個非常簡單的操作,但它有點破解。

的維護的方式

2)可替換地,Collections.sort方法以一個比較器作爲輸入 - 你可以很容易地編寫實現所需的分選的比較的比較器的定製,通過鑄造投入學生類,並直接返回數據比較。

第二種解決方案更加模塊化並且可維護,除非按日期進行比較是您的應用程序的核心部分。

+1

而從Java 5開始,在比較器中大部分時間不再需要鑄造了。 ;) – Stefan 2011-12-23 22:18:56

2

在學生課中實施Comparable接口。然後使用 Collections.sort(list);

1

你可以做一些事情如下:

要麼使類實現Comparable

public class Student implements Comparable<Student> { 
    private Date joinDate; 
    private String id; 

    //... 

    @Override 
    public int compareTo(Student o) { 
     int result = joinDate.compareTo(o.joinDate); 
     if(result != 0) { 
      return result; 
     } 
     return id.compareTo(o.id); 
    }  
} 

或者使用Comparator

Comparator<Student> comparator = new Comparator<Student>() { 

    @Override 
    public int compare(Student o1, Student o2) { 
     int result = o1.getJoinDate().compareTo(o2.getJoinDate()); 
     if (result != 0) { 
      return result; 
     } 
     return o1.getId().compareTo(o1.getId()); 
    } 
}; 
1

Collections類有一種方法,它接受Comparator作爲參數:

List<Student> students; 

/* ...students list instantiated and populated somewhere along here... */ 

Collections.sort(students, new Comparator<Student>() { 

    @Override 
    public int compare(Student student1, Student student2) { 
     return student1.joinDate().compareTo(student2.joinDate()); 
    } 
}); 

我要補充的是,如果你的列表的確聲明爲Object通用的,你將不得不做很多鑄造。該列表應聲明爲Student,並且您應該有其他非學生對象列表。

1

你可以這樣做一個的方法有兩種:

1)在對象上實現的Comparable接口並調用`Collections.sort(yourList);」。

或者

2)實施Comparator接口的新類(讓我們假設你調用該類StudentDateComparator然後你可以的調用Collections.sort(yourList,新StudentDateComparator());`

我。一般比較喜歡,因爲它讓我保持分類代碼獨立於數據對象,它排序後者。

1
  1. 如果基於ID字段學生類實現可比,使用Collections.sort()與列表爲單個參數。

  2. 否則,實現一個比較器,該比較器使用它們的ID比較對象,並將它用作Collections.sort()的第二個參數。

相關問題