import java.util.ArrayList;
//定义一个点(Point)的类,x和y分别为第一象限的像素点,输入一些这样的点,然后按照升序输出这些点集(比较x2+y2的大小)。
public class Point {
private int x; //x的值
private int y;//y的值
private int dis;//计算 x^2 * y^2
public int getDis() {
return dis;
}
public void setDis(int dis) {
this.dis = dis;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Point(){
}
public Point(int x, int y){
this.x = x;
this.y = y;
}
public int distance(){
return getX() * getX() + getY() * getY();
}
}
Test类
import java.util.*;
//定义一个点(Point)的类,x和y分别为第一象限的像素点,
//输入一些这样的点,然后按照升序输出这些点集(比较x2+y2的大小)。
public class Test {
public static void main(String[] args) {
ArrayList<Point> list = new ArrayList<>();//创建一个Point集合
Point p1 = new Point(8,2); //添加X,Y的坐标
Point p2 = new Point(3,4);
Point p3 = new Point(7,1);
Point p4 = new Point(5,2);
Point p5 = new Point(6,9);
list.add(p1);// 将对象插入集合
list.add(p2);
list.add(p3);
list.add(p4);
list.add(p5);
p1.setDis(p1.distance()); // 计算 x^2 * y^2 传入dis
p2.setDis(p2.distance());
p3.setDis(p3.distance());
p4.setDis(p4.distance());
p5.setDis(p5.distance());
System.out.println("排序前"); //遍历
for (int i = 0; i < list.size(); i++) {
System.out.println("x:"+list.get(i).getX()+",y:"+list.get(i).getY() + ",distance:" + list.get(i).getDis());
}
//自定义匿名类实现比较器
Comparator<Point> comparator = new Comparator<Point>() {
public int compare(Point o1, Point o2) {
return o1.getDis() - o2.getDis() ;
}
};
Collections.sort(list, comparator);//排序
System.out.println("排序后");
for (int i = 0; i < list.size(); i++) {
System.out.println("x:"+list.get(i).getX()+",y:"+list.get(i).getY() + ",distance:" + list.get(i).getDis());
}
}
}