某些情况下,匿名内部类有它的优势。你不喜欢可以自己创建一个类实现java.util.Comparator接口也可行啊
大概的代码如下:// 比较器实现类
public class DemoComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
// 比较的逻辑代码
if (o1 instanceof Person && o2 instanceof Person) {
Person p1 = (Person) o1;
Person p2 = (Person) o2;
int temp = p1.getName().length() - p2.getName().length();
return temp == 0 ? p1.getAge() - p2.getAge() : temp;
} else {
throw new ClassCastException("类型不匹配");
}
}
}然后在另一个地方使用它: public static void main(String[] args) {
TreeSet ts = new TreeSet(new DemoComparator());
}
大概的代码如下:// 比较器实现类
public class DemoComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
// 比较的逻辑代码
if (o1 instanceof Person && o2 instanceof Person) {
Person p1 = (Person) o1;
Person p2 = (Person) o2;
int temp = p1.getName().length() - p2.getName().length();
return temp == 0 ? p1.getAge() - p2.getAge() : temp;
} else {
throw new ClassCastException("类型不匹配");
}
}
}然后在另一个地方使用它: public static void main(String[] args) {
TreeSet ts = new TreeSet(new DemoComparator());
}
public int compare(Object o1, Object o2) {
return 0;
}
});
public void run(){
//TODO
}
};
还有,不需要再compare方法里面用强制转换,new Comparator<Person>() 用上泛型即可