基本上,我有一个名为“Employees”的容器类,其中包含一个 ArrayList。此 ArrayList 包含“Employee”对象,而“Employee”对象又包含“EmployeeData”对象,而“EmployeeData”对象又包含 String 对象,例如“first”或“last”(员工姓名)。
这是 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 执行快速排序,以便其中的“Employee”对象根据字符串对象“last”按字母顺序排列?好像有点复杂!
这是我的类的基本设计:
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”类中实现“排序”,以便它按“EmployeeData”类的“last”变量对 ArrayList 进行排序。
最佳答案
你可以做一个比较器,比如:
public class MyComparator implements Comparator<Employee>
{
public int compare(Employee e1, Employee e2)
{
return e1.getData().getLast().compareTo(e2.getData().getLast());
}
}
然后用它来对列表进行排序。
Collections.sort(myList, new MyComparator());
或者,您可以使用 TreeSet 通过此比较器对插入进行排序,或者使 Employee 成为可比较的对象以使用 Collections 或 SortedSet 进行排序。
public class Employee implements Comperable<Employee>
{
...
public int compareTo(Employee e)
{
return this.getData().getLast().compareTo(e.getData().getLast());
}
...
}
关于java - 在 Java 中,如何对排序字段深度为多层的对象 ArrayList 进行快速排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3935827/