java - 在 Java 中,如何对排序字段深度为多层的对象 ArrayList 进行快速排序?

标签 java arrays sorting arraylist quicksort

基本上,我有一个名为“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/

相关文章:

java - 如何创建具有多个页面的 Swing 应用程序

java - Gradle构建在 list 中声明了一个新的Activity,但没有名称,从而产生了一个错误

mysql - 如何在 codeigniter 中使用 my_controller 显示对象的属性

c++ - 如何对整数进行排序并将它们放在列表中

MySQL:我需要在查询中获取项目的偏移量

java - 将 Json 转换为包含类型变量(某些子类)的 Java 对象

java - 在不同对象中执行操作后修改对象的最佳方法

c - C 中的数组增量类型 - array[i]++ 与 array[i++]

java - 猜谜游戏不计算相同的猜测两次

java - 双轴快速排序和快速排序有什么区别?