Table of Contents

The Comparable Interface for Sorting Objects


Objectives


Comparable & Sorting

         1. positive - this object is greater than obj1
         2. zero - this object equals to obj1
         3. negative - this object is less than obj1

Employee Class example

         // The original Employee class:
         public class Employee {
             private int empId;
             private String name;
             private int age;

             public Employee(int empId, String name, int age) {
                 // set values of fields
             }
             // getters & setters
         }
         import java.util.*;

         public class Util {
             
             public static ArrayList<Employee> getEmployees() {
                 
                 ArrayList<Employee> col = new ArrayList<Employee>();
                 
                 col.add(new Employee(5, "Frank", 28));
                 col.add(new Employee(1, "Jorge", 19));
                 col.add(new Employee(6, "Bill", 34));
                 col.add(new Employee(3, "Michel", 10));
                 col.add(new Employee(7, "Simpson", 8));
                 col.add(new Employee(4, "Clerk",16 ));
                 col.add(new Employee(8, "Lee", 40));
                 col.add(new Employee(2, "Mark", 30));
                 
                 return col;
             }
         }
         public class Employee implements Comparable<Employee> {
             private int empId;
             private String name;
             private int age;
             
             /**
              * Compare a given Employee with this object.
              * If employee id of this object is 
              * greater than the received object,
              * then this object is greater than the other.
              */

             public int compareTo(Employee o) {
                 return this.empId - o.empId ;
             }

             // ....
         }
         import java.util.*;

         public class TestEmployeeSort {
             
             public static void main(String[] args) {     
                 ArrayList coll = Util.getEmployees();  // use static Util.getEmployees()
                 Collections.sort(coll); // sort method
                 printList(coll);
             }
             
             private static void printList(ArrayList<Employee> list) {
                 System.out.println("EmpId\tName\tAge");
                 for (Employee e: list) {
                     System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
                 }
             }
         }

Song/Playlist Class example