I know those interfaces use for sort objects in a Collection. But I am having doubt of the real difference of those. One fact i read is use comparable when you want to compare two objects with out the current object (this).
But my problem is even with comparator we compare same object type know.
What is really the difference here. I am confused. Suppose the following example,
class Person implements Comparable<Person> {
private String firstName;
private String lastName;
private int age;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int compareTo(Person anotherPerson){
int anotherPersonAge =anotherPerson.getAge();
return this.age - anotherPersonAge;
}
}
If i use comparator i would have a class implement the comparator and instead of this.age, it has person.age. So what is so different here?
public class LastNameComparator implements Comparator<Person> {
public int compare(Person person, Person anotherPerson) {
int age1 = person.getAge();
int age2 = anotherPerson.getAge();
return age1 - age2;
}
}
I dont know the internal logic Collections.sort use. Please justify the above point if so with regard to that.
Also i believe no need to return -1,1 or 0 right. Above implementation is also valid right? One problem i am having is if we return 1 how can the list order the item according to ascending or descending order? I thought its the difference take into consider and order them according to the difference.