Modify the Point class from Chapter 8 so that it defines a natural ordering by implementing the Comparable interface. Compare the Points by y-major order; that is, points with smaller y-coordinate values should come before those with higher y-coordinate values. Break ties by comparing x-coordinate values.
// Point.java (modified Point class)
public class Point implements Comparable
{
// refer the textbook for the Point class
/* implementation of the compareTo method of
the Comparable interface */
public int compareTo(Point other)
{
if(y < other.y)
return -1;
else if(y > other.y)
return 1;
else if(x < other.x)
return -1;
else if(x > other.x)
return 1;
else
return 0;
}
}
// PointDemo.java
import java.util.ArrayList;
import java.util.Collections;
public class PointDemo
{
public static void main(String[] args)
{
Point p1 = new Point(2, 8);
Point p2 = new Point(7, 2);
Point p3 = new Point(3, 4);
Point p4 = new Point(1, 4);
ArrayList points = new ArrayList();
points.add(p1);
points.add(p2);
points.add(p3);
points.add(p4);
System.out.println("Points in the list before soring: "
+ points);
Collections.sort(points);
System.out.println("Points in the list after soring: "
+ points);
}
}
Output :
Points in the list before soring: [(2, 8), (7, 2), (3, 4), (1, 4)]
Points in the list after soring: [(7, 2), (1, 4), (3, 4), (2, 8)]