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;
}
}
}