/* * file: Point.java * * This extends the Point.java example in the clone directory. * We now want our points to be comparable as well. * * @author Chee Yap * Honors Basic Algorithms, Fall 2000 */ class Point implements Cloneable, Comparable // if missing, get runtime error { public int x, y; Point() { x = 0; y = 0; }//Point() Point(int a, int b){ x = a; y = b; }//Point(a,b) public int compareTo(Object oo){ // return -1 is this is less than o. Point o = (Point) oo; // casting is necessary if ((o.x < this.x) || (o.x == this.x && o.y < this.y)) return 1; if ((o.x > this.x) || (o.x == this.x && o.y > this.y)) return -1; return 0; } public static void main (String[] args) throws Exception { Point p = new Point(0,0); Point q = p; // only reference is copied! p.x = 1; System.out.println( "References p and q point to the same Point. Is p == q? "); if (p == q) System.out.println(" Yes, RIGHT!"); else System.out.println(" No, ERROR!"); System.out.println( "References r is a clone of p. Is p == r? "); Point r = (Point)p.clone(); if (p == r) System.out.println(" Yes, ERROR!"); else System.out.println(" No, RIGHT!"); System.out.println("Comparing (1,0) to (1,0) returns " + p.compareTo(q) ); p = new Point(1,1); System.out.println("Comparing (1,1) to (1,0) returns " + p.compareTo(q) ); System.out.println("Comparing (1,0) to (1,1) returns " + q.compareTo(p) ); } //main method } //Point Class