Header Ads

  • Breaking Now

    Code Snippets: Using java.lang.Comparable Interface

    import java.util.Arrays;
    class Employee implements Comparable {
    String empName;
    String empCode;
    int totalMarks;
    double totalSalary;
    /**
    * @return
    */
    public String getName() {
    return empName;
    }
    /**
    * @return
    */
    public String getEmpCode() {
    return empCode;
    }
    /**
    * @param strEmpName
    */
    public void setName(String strEmpName) {
    empName = strEmpName;
    }
    /**
    * @param strEmpCode
    */
    public void setEmpCode(String strEmpCode) {
    empCode = strEmpCode;
    }
    public double getTotalSalary() {
    return totalSalary;
    }
    public void setTotalSalary(double totalSalary) {
    this.totalSalary = totalSalary;
    }
    // sorting in desecending order of salary
    public int compareTo(Object o) {
    Employee employee = (Employee) o;
    int comp = 0;
    if (this.getTotalSalary() < employee.getTotalSalary()) {
    comp = -1;
    } else if (this.getTotalSalary() > employee.getTotalSalary()) {
    comp = 1;
    }
    return comp;
    }
    }
    //Sorts salaries of specified employess in ascending order
    public class SortData {
    public static void main(String[] args) {
    Employee[] employee = new Employee[3];
    employee[0] = new Employee();
    employee[0].setName("John Adams");
    employee[0].setEmpCode("3");
    employee[0].setTotalSalary(2100.78);
    employee[1] = new Employee();
    employee[1].setName("Gregory Peck");
    employee[1].setEmpCode("2");
    employee[1].setTotalSalary(1234.45);
    employee[2] = new Employee();
    employee[2].setName("John Travolta");
    employee[2].setEmpCode("1");
    employee[2].setTotalSalary( 1533.87);
    System.out.println("Before Comparator");
    for (int i = 0; i < employee.length; i++) {
    System.out.println("Rank:" + (i + 1) + "   " + employee[i].getName()
    + " Total Salary: " + employee[i].getTotalSalary());
    }
    Arrays.sort(employee);
    System.out.println("After Comparator");
    for (int i = 0; i <  employee.length; i++) {
    System.out.println("Rank:" + (i + 1) + "   " + employee[i].getName()
    + " Total Salary: " + employee[i].getTotalSalary());
    }
    }
    } 

    No comments

    Post Top Ad

    Post Bottom Ad