TreeSet的构造函数的比较器可以写成匿名累不累么?

cacagege 2015-01-14 09:27:01
TreeSet 的构造函数可以传一个比较器进去,为什么把这个比较器写成匿名累不累,eclipse 表示认不到。。不知道为什么。。。
TreeSet ts = new TreeSet(new Comparator(){
public int compare(Object o1, Object 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("类型不匹配");
});
...全文
293 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
ChangeZ_ 2015-01-15
  • 打赏
  • 举报
回复
因为方便,就好比你要使用一个线程而不用写整个线程类一样:

new Runnable(){
public void run(){
//TODO
}
};
  • 打赏
  • 举报
回复
Set s = new TreeSet(new Comparator() {
			public int compare(Object o1, Object o2) {
				
				return 0;
			}
		});
  • 打赏
  • 举报
回复
我记得可以用的。
淡定的峰哥 2015-01-15
  • 打赏
  • 举报
回复
lz 你的代码在小括号前面少一个花括号,另外else分支最好也用花括号括起来 还有,不需要再compare方法里面用强制转换,new Comparator<Person>() 用上泛型即可
Leonhe2022 2015-01-14
  • 打赏
  • 举报
回复
某些情况下,匿名内部类有它的优势。你不喜欢可以自己创建一个类实现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());
	}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧