Java、对面板上的点进行排序

 

package collection;

import java.util.Arrays;
import java.util.Comparator;

public class Exercise20_04 {

    public static void main(String[] args) {
        Point[] points1 = new Point[100];
        for (int i = 0; i < points1.length; i++)    //随机创建一百个Point对象
            points1[i] = new Point(Math.random() * 100, Math.random() * 100);

        Point[] points2 = points1.clone();
        Arrays.sort(points2, new CompareY());   //升序排序
        Arrays.sort(points1);

        System.out.println("Sorted by x ordinate:\t\t\tSorted by y ordinate:");
        for (int i = 0; i < points1.length; i++)
            System.out.println(String.format("%10s\t\t\t\t\t%10s", points1[i], points2[i]));

    }

}

/** Point类-实现Comparable接口 */
class Point implements Comparable<Point> {
    private double x, y;    //x, y坐标

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }

    /** 比较Point(先比较x坐标,后比较y坐标) */
    @Override
    public int compareTo(Point o) {
        if (this.x < o.getX())
            return -1;
        else if (this.x > o.getX())
            return 1;
        else {
            if (this.y < o.getY())
                return -1;
            else if (this.y > o.getY())
                return 1;
            else
                return 0;
        }
    }

    @Override
    public String toString() {
        return String.format("(%.2f, %.2f)", x, y);
    }

    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }
}

/** Point类比较器 */
class CompareY implements Comparator<Point> {

    /** 比较Point(先比较y坐标,后比较x坐标) */
    @Override
    public int compare(Point o1, Point o2) {
        if (o1.getY() > o2.getY())
            return 1;
        else if (o1.getY() < o2.getY())
            return -1;
        else {
            if (o1.getX() > o2.getX())
                return 1;
            else if (o1.getX() < o2.getX())
                return -1;
            else
                return 0;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值