class Employee implements Comparable{
private String name;
private String gender;
Employee(String name, String gender) {
this.name = name;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String toString() {
return this.getName() + " : " + this.getGender();
}
@Override
public int compareTo(Object o) {
int gendarComp=this.getGender().compareTo(((Employee)o).getGender());
return (gendarComp!=0?gendarComp:this.name.compareTo(((Employee)o).getName()));
}
}
class EmployeeExec {
public static void main(String[] args) {
List allEmpls = new ArrayList();
allEmpls.add(new Employee("vijay", "m"));
allEmpls.add(new Employee("balaji", "m"));
allEmpls.add(new Employee("shaifali", "f"));
allEmpls.add(new Employee("archana", "f"));
allEmpls.add(new Employee("alala", "m"));
allEmpls.add(new Employee("kiran", "f"));
sortEmployees(allEmpls);
}
public static void sortEmployees(List allEmpls) {
Collections.sort(allEmpls);
System.out.println(allEmpls);
}
}
Can anyone help me in understanding how it is working? what is the funda to sort? I kept some println statements to see, but I don't really understand how it is getting called. I know its working with merge sort. But how?
The sorting is based on the return value of compareTo
(slightly reformatted for readability):
@Override
public int compareTo(Object o) {
int gendarComp = this.getGender().compareTo(((Employee)o).getGender());
return (gendarComp != 0
? gendarComp
: this.name.compareTo( ((Employee)o).getName() )
);
}
The logic is apparently to compare values of getGender()
and return that comparison unless they test equal. If they are equal, it returns the result of comparing names.
As an aside: If this is your code, it would be better to use generics instead of raw types. Declare
class Employee implements Comparable<Employee> {...
Then declare the compareTo
method with the signature:
@Override
public int compareTo(Employee o) {...
and you can dispense with the casts inside the method (as well as improve type safety in client code).