In Java, How do you quicksort an ArrayList of objects in which the sorting field is multiple layers deep?

前端 未结 4 943
终归单人心
终归单人心 2021-02-10 13:51

Basically, I have a Container class called \"Employees\" which has in it an ArrayList. This ArrayList contains \"Employee\" objects, which in turn contain \"EmployeeData\" objec

4条回答
  •  萌比男神i
    2021-02-10 14:38

    The best practice is to encapsulate the sorting logic in the class stored in the ArrayList, Employee in this case. Implement Comparable by creating a compareTo(Employee) method.

    import java.util.*;
    
    public class Employee  implements Comparable {
        public EmployeeData Data;
    
        public Employee(String first, String last)
        {
            Data = new EmployeeData(first, last);
        }
    
        public int compareTo(Employee other)
        {
            return Data.Last.compareTo(other.Data.Last);
        }
    
        public String toString() {
            return Data.First + " " + Data.Last;
        }
    
        public static void main(String[] args) throws java.io.IOException {
            ArrayList list = new ArrayList();
            list.add(new Employee("Andy", "Smith"));
            list.add(new Employee("John", "Williams"));
            list.add(new Employee("Bob", "Jones"));
            list.add(new Employee("Abraham", "Abrams"));
            Collections.sort(list);
            for (int i = 0; i < list.size(); i++)
            {
                System.out.println(list.get(i));
            }
            System.in.read();
        }
    }
    
    public class EmployeeData {
        public String First;
        public String Last;
        public EmployeeData(String first, String last)
        {
            First = first;
            Last = last;
        }
    }
    

    Output:

    Abraham Abrams
    Bob Jones
    Andy Smith
    John Williams
    

提交回复
热议问题