开发者社区 问答 正文

java 匿名内部类实现接口,运用Collections.sort()方法出错? 400 报错

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这里会出现编译错误啊?

展开
收起
爱吃鱼的程序员 2020-05-31 00:17:57 821 分享 版权
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    sort接收的是一个List参数而不是Set... 这个既然都是用IDE开发了代码提示的时候或者查文档不是写的很清楚吗
    ######哦,也就是说Collections.sort()方法里面传入的参数只可以是List对象,不可以是Set对象啦,是吧?######sort( List<T> list, Comparator<? super T> c)

              根据指定比较器产生的顺序对指定列表进行排序。

    从api文档拷贝过来的。

    ######参数是List######哦
    2020-05-31 00:17:58
    赞同 展开评论