我知道这些接口用于对集合中的对象进行排序。但我怀疑这些的真正区别。我读到的一个事实是,当您想比较两个对象而不是当前对象(this)时使用可比较。
但我的问题是即使使用比较器我们比较相同的对象类型知道。
这里真正的区别是什么。我很困惑。假设以下示例,
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;
}
}
如果我使用比较器,我将有一个类实现比较器,而不是 this.age,它有 person.age。那么这里有什么不同呢?
public class LastNameComparator implements Comparator<Person> {
public int compare(Person person, Person anotherPerson) {
int age1 = person.getAge();
int age2 = anotherPerson.getAge();
return age1 - age2;
}
}
我不知道 Collections.sort 使用的内部逻辑。如果是的话,请证明上述观点是正确的。
我也相信没有必要返回 -1,1 或 0 对。上面的实现也是有效的吧?我遇到的一个问题是,如果我们返回 1,列表如何根据升序或降序对项目进行排序?我认为它的差异考虑并根据差异对其进行排序。