“您将如何按 id 或名称对员工对象的集合进行排序”。为此我们可以使用两个界面,即,Comparator and Comparable.
这似乎是常见的面试问题之一
但是我看不出为什么我应该同时使用这两种方法来对员工对象进行排序
我一直在思考什么comparator
是Comparable
做不到的。我知道如果对象(比较的实例变量)具有自然顺序,那么comparable
是正确的选择。但是如果需要自定义排序(例如字符串长度),那么可以comparator.
在这里写一个我的观点,comparator
只有当客户想按照其他标准对数据进行排序时才需要。例如,我将实现一个Employee class
使用. 但如果客户想按(名称)对 Employee 对象进行排序,他将实现为具体类或匿名排序。我在这里有什么遗漏吗?id
comparable interface
String
comparator
例如,在下面的代码中,对于 Person 对象,我的 compareTo 方法,比较年龄并对其进行排序 在 compare 方法中,我使用 String 长度(人名)进行排序。理论上,我可以在下面实现的 compareTo 方法中完成这两者。
最后,与其他方法相比,以下其中一项是否有任何额外的好处我以两种方式实现了比较器 1. 作为被注释掉的静态方法 2. 作为被注释掉的主要方法中的匿名对象(?) 3. 制作一个实现比较器并在 collections.sort() 中调用该类的实例的新类——我在这里没有做过
(The commented-out parts of the code works. They are just different implementations)
mport java.util.Collections;
import java.util.Comparator;
import java.util.*;
public class PersonComparator implements Comparable{
private String name;
private int age;
public PersonComparator(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "name=" + name + ", age=" + age;
}
/*@Override
public int compareTo(Object obj) {
if (!(obj instanceof PersonComparator)) {
throw new ClassCastException("Invalid object");
}
PersonComparator p2 = (PersonComparator)obj;
return this.age-p2.age;
}*/
/*Alternative CompareTo that checks for both age and name*/
public int compareTo(Object obj) {
if (!(obj instanceof PersonComparator)) {
throw new ClassCastException("Invalid object");
}
PersonComparator p2 = (PersonComparator)obj;
if (this.age!=p2.age){
return this.age-p2.age;
}
else {
return (this.name.length()-p2.name.length());
}
}
/*public static Comparator nameLengthComparator
= new Comparator() {
@Override
public int compare(Object obj1, Object obj2) {
if (!(obj1 instanceof PersonComparator) || !(obj2 instanceof PersonComparator)){
throw new ClassCastException("Invalid object");
}
else {
PersonComparator p1 = (PersonComparator)obj1;
PersonComparator p2 = (PersonComparator)obj2;
return p1.name.length()-p2.name.length();
}
}
};*/
public static void main(String[] args){
PersonComparator p1 = new PersonComparator("Alexander", 45);
PersonComparator p2 = new PersonComparator("Pat", 27);
PersonComparator p3 = new PersonComparator("Zacky", 45);
PersonComparator p4 = new PersonComparator("Rake", 34);
List<PersonComparator> list = new ArrayList<PersonComparator>();
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
System.out.println("Before sorting "+ list);
Collections.sort(list);
//System.out.println("After sorting by age "+ list);
//System.out.println("Before sorting "+ list);
//Collections.sort(list, nameLengthComparator);
System.out.println("After sorting by name length "+ list);
/*Collections.sort(list, new Comparator<PersonComparator>() {
@Override
public int compare(PersonComparator p1, PersonComparator p2) {
return p1.name.length()-p2.name.length();
}
}
);*/
System.out.println("After sorting by name length "+ list);
}
}
谢谢