Question
Implement the following steps: 1. Modify the class Rectangle from chapter 9 such that it implements the Comparable interface. Comparable interface defines only one method, compareTo(). Read API documentation to learn the requirements for this method. Add a toString() method to help with the output. 2. Write an application that defines an array of 5 Rectangle objects. This application should initialize the 5 objects with different data and then sort the array by calling Arrays.sort() method. Finally, the application should display the sorted array. Arrays class is located in the java.util package.
Explanation / Answer
import java.util.Arrays; class Test{ public static void main(String[] args) { Rectangle rectangles[] = new Rectangle[5]; Rectangle r1 = new Rectangle(12,2); Rectangle r2 = new Rectangle(2,4); Rectangle r3 = new Rectangle(3.5,4.1); Rectangle r4 = new Rectangle(32,1); Rectangle r5 = new Rectangle(6.5,2.4); rectangles[0] = r1; rectangles[1] = r2; rectangles[2] = r3; rectangles[3] = r4; rectangles[4] = r5; System.out.println("Before sort:"); for(Rectangle r : rectangles) System.out.println(r); Arrays.sort(rectangles); System.out.println("After sort:"); for(Rectangle r : rectangles) System.out.println(r); } } /** * The Rectangle class stores and manipulates * data for a rectangle. */ class Rectangle implements Comparable { private double length; private double width; /** * Constructor */ public Rectangle(double len, double w) { length = len; width = w; } /** * The setLength method accepts an argument * which is stored in the length field. */ public void setLength(double len) { length = len; } /** * The setWidth method accepts an argument * which is stored in the width field. */ public void setWidth(double w) { width = w; } /** * The set method accepts two arguments * which are stored in the length and width * fields. */ public void set(double len, double w) { length = len; width = w; } /** * The getLength method returns the value * stored in the length field. */ public double getLength() { return length; } /** * The getWidth method returns the value * stored in the width field. */ public double getWidth() { return width; } /** * The getArea method returns the value of the * length field times the width field. */ public double getArea() { return length * width; } @Override public String toString() { return "Rectangle{" + "length=" + length + ", width=" + width + '}'; } @Override public int compareTo(Rectangle o) { return (int) ((length+width)-(o.length+o.width)); } }