62,614
社区成员
发帖
与我相关
我的任务
分享
new Runnable(){
public void run(){
//TODO
}
};
Set s = new TreeSet(new Comparator() {
public int compare(Object o1, Object o2) {
return 0;
}
});
// 比较器实现类
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());
}