Query on compareTo method

Following is the program to sort the employees on the Name basis

import java.util.*;

class EmployeeSortTest

{

public static void main ( String[] tam )

{

// Array of Employees

Employee[] a = new Employee[3];

a[0] = new Employee("Tam",350000);

a[1] = new Employee("Dravid",500000);

a[2] = new Employee("Sachin",700000);

// Sorting the Employees with name basis using Arrays utility class

Arrays.sort(a);

for( Employee x : a)

System.out.println(" Name = " + x.getName() +

"Salary = " + x.getSalary());

}

}

class Employee implements Comparable

{

public Employee(String n, double s )

{

name = n;

salary = s;

}

public int compareTo(Employee other)

{

return name.compareTo(other.name);

}

public String getName()

{

return name;

}

public double getSalary()

{

return salary;

}

private double salary;

private String name;

}

My problem is I also want to sort the Employees on the Salary basis without modifying this existing code.

i.e to have an another version of compareTo() method in this class that implements Comparable interface

which sort on salary basis

public int compareTo(Employee other)

{

if ( salary > other.salary) return 1;

if ( salary < other.salary) retrurn -1;

return 0;

}

But compiler reports that compareTo() is already defined in Employee

Pls give solution to this

[1591 byte] By [tamizh88a] at [2007-11-27 8:30:39]
# 1
Yes you can only implement Comparable once.What you can do is provide a Comparator to the sort. See the sort(Object[] a, Comparator c) method of Arrays and the Comparator interface API.
cotton.ma at 2007-7-12 20:25:47 > top of Java-index,Java Essentials,New To Java...
# 2

@OP: Without using generics, you cannot writepublic int compareTo(Employee other)

.

You should either do it like this:class Employee implements Comparable {

// ...

public int compareTo(Object o) {

// cast

// compare

}

// ...

}

or, with generics (JDK 1.5+), like this:class Employee implements Comparable<Employee> {

// ...

public int compareTo(Employee that) {

// compare

}

// ...

}

prometheuzza at 2007-7-12 20:25:47 > top of Java-index,Java Essentials,New To Java...