java 匿名内部类实现接口,运用Collections.sort()方法出错? 400 报错
package day07;
import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Set;
public class Point { private int x, y; public Point(int x, int y){ this.x=x; this.y=y; } public void setX(int x){ this.x=x; } public void setY(int y){ this.y=y; } public int getX(){ return x; } public int getY(){ return y; } public String toString(){ return x+","+y; } public boolean equals(Point p){//重写了equals()方法,需重写hashCode()方法 if(p==null) return false; if(p==this) return true; if(p instanceof Point){ Point o=(Point) p; return this.x==o.x&&this.y==o.y; } else{ return false; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Point other = (Point) obj; if (x != other.x) return false; if (y != other.y) return false; return true; }
public static void main(String[] args) {
Set<Point> set=new HashSet<Point>();
set.add(new Point(7, 2));
set.add(new Point(3, 1));
set.add(new Point(1, 9));
System.out.println(set);
System.out.println(set.contains(new Point(7, 2)));
Collections.sort(set, new Comparator<Point>(){//出错!!!?
public int compare(Point p1, Point p2){
return (p1.x*p1.x+p1.y*p1.y)-(p2.x*p2.x+p2.y*p2.y);
}
});
System.out.println(set);
}
}
为什么Collentions.sort这里会出现编译错误啊?
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
sort接收的是一个List参数而不是Set... 这个既然都是用IDE开发了代码提示的时候或者查文档不是写的很清楚吗
######哦,也就是说Collections.sort()方法里面传入的参数只可以是List对象,不可以是Set对象啦,是吧?######sort( List<T> list, Comparator<? super T> c)
根据指定比较器产生的顺序对指定列表进行排序。
从api文档拷贝过来的。
######参数是List######哦