import java.util.*;
class Employee implements Comparable
{
int EmpID;
String Ename;
double Sal;
static int i;
public Employee(String ename, double sal) {
EmpID = i++;
Ename = ename;
Sal = sal;
}
public String toString() {
return "EmpID " + EmpID + "\n" + "Ename " + Ename + "\n" + "Sal" + Sal;
}
public int compareTo(Employee o1) {
if (this.Sal == o1.Sal)
return 0;
else if ((this.Sal) > o1.Sal)
return 1;
else
return -1;
}
}
public class ComparableDemo{
public static void main(String[] args) {
List<Employee> ts1 = new ArrayList<Employee>();
ts1.add(new Employee ("Tom",40000.00));
ts1.add(new Employee ("Harry",20000.00));
ts1.add(new Employee ("Maggie",50000.00));
ts1.add(new Employee ("Chris",70000.00));
Collections.sort(ts1);
Iterator itr = ts1.iterator();
while(itr.hasNext()){
Object element = itr.next();
System.out.println(element.toString() + "\n");
}
}
}
In the above program i am getting problem to understand the use of sort() and compareTo() method.How are they linked each other.
In this case i am getting one compilation error*******
C:\jdk1.5.0\bin>javac ComparableDemo.java
ComparableDemo.java:2: Employee is not abstract and does not override abstract m
ethod compareTo(java.lang.Object) in java.lang.Comparable
class Employee implements Comparable
^
Note: ComparableDemo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
But as i know i have done correct implementation of compareTo() according to it's signature.
One more thing i want to ask that how toString() method is invoked even it is not invoked explicitly.
Thanks