tru*_*ktr 4 java arrays sorting arraylist quicksort
基本上,我有一个名为"Employees"的Container类,其中包含一个ArrayList.此ArrayList包含"Employee"对象,后者又包含"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.
Run Code Online (Sandbox Code Playgroud)
我将如何在ArrayList上执行快速排序,以便其中的"Employee"对象基于String对象"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...
}
Run Code Online (Sandbox Code Playgroud)
如您所见,这些是课程.我不知道如何在"Employees"类中实现"sort",以便它通过"EmployeeData"类的"last"变量对ArrayList进行排序.
Pet*_*ese 11
你可以做一个比较器,如:
public class MyComparator implements Comparator<Employee>
{
public int compare(Employee e1, Employee e2)
{
return e1.getData().getLast().compareTo(e2.getData().getLast());
}
}
Run Code Online (Sandbox Code Playgroud)
然后用它来排序列表.
Collections.sort(myList, new MyComparator());
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用TreeSet对使用此比较器的插入进行排序,或者使Employee成为可比较的对象,以使用Collections或SortedSet进行排序.
public class Employee implements Comperable<Employee>
{
...
public int compareTo(Employee e)
{
return this.getData().getLast().compareTo(e.getData().getLast());
}
...
}
Run Code Online (Sandbox Code Playgroud)