基本上,我有一個名爲「Employees」的Container類,裏面有一個ArrayList。這個ArrayList包含「Employee」對象,該對象又包含「EmployeeData」對象,而該對象又包含String對象,如「first」或「last」(這是員工姓名)。在Java中,如何快速排列排序字段爲多層的對象的ArrayList?
這裏的ArrayList的結構圖:
ArrayList[Employee] emps ==> 1:Many ==> Employee emp
Employee emp ==> 1:1 ==> EmployeeData data
EmployeeData data ==> 1:2 ==> String last // A string that contains employee's last name.
如何在世界上我會在ArrayList中進行快速排序,以便在它的「僱員」的對象是按字母順序基於字符串對象「持續」?看起來有點複雜!
這是我班的一個基本設計:
class Employees{
//data:
private ArrayList<Employee> emps = new ArrayList<Employee>();
//Some constructors go here
//Methods to add, remove, toString, etc, go here
public /*output a sorted ArrayList?*/ sort(){
// Some kind of "quicksort" in here to modify or create a new ArrayList sorted by employee's las name...
}
}
class Employee{
//data:
EmployeeData data;
// Some methods to construct and modify EmployeeData data.
}
class EmployeeData{
//data:
String first, last; // I wish to sort with "last". How do you do it?
double payrate, hours;
//...methods...
}
正如你所看到的,這些都是類。我不知道如何在「Employees」類中實現「sort」,以便通過「EmployeeData」類的「last」變量對ArrayList進行排序。
謝謝傑森!多好的答案。這應該讓我開始。 出於好奇,Collections.sort()實現了一個快速排序嗎? – trusktr 2010-10-14 18:32:10
不,它是實現「修改mergesort」 - > http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Collections.html#sort%28java.util.List%29 – 2012-05-24 20:05:45