Define a Rectangle class that provides getLength and getWidt
Define a Rectangle class that provides getLength and getWidth methods. Using the findMax routine given below, write a program that creates an array of Rectangles and finds the largest Rectangle first on the basis of area, and then on the basis of perimeter.
findMax Eample:
//Generic findMax, with a function object.
//Precondition: a.size() > 0.
public static <AnyType> AnyType findMax(AnyType [] arr, Comparator<? super AnyType> cmp) {
int maxIndex = 0;
for(int i = 1; i < arr.size(); i++)
if(cmp.compare( arr[i], arr[maxIndex]) > 0) maxINdex = i;
return arr[maxIndex]; }
Need to use generics
Solution
public static <E> E findMax(E[] arr, Comparator<? super E> cmp) {
int maxIndex = 0;
for (int i = 1; i < arr.length; i++) {
if (cmp.compare(arr[i], arr[maxIndex]) > 0) {
maxIndex = i;
}
}
return arr[maxIndex];
}
// comparater to compare the area of the rectangle//
private static class AreaComparator implements Comparator<Rectangle> {
public int compare(Rectangle lhs, Rectangle rhs) {
return Double.compare(lhs.getArea(), rhs.getArea());
}
}
// Get area//
private static class Rectangle {
private double width;
private double height;
public Rectangle(double width, double height) {
super();
this.width = width;
this.height = height;
}
public double getArea() {
return width * height;
}
public String toString() {
return \"Rectangle [width=\" + width + \", height=\" + height + \"]\";
}
}
// main method//
public static void main(String[] args) throws Exception {
System.out.println(findMax(new Rectangle[] { new Rectangle(2, 3), new Rectangle(4, 5) }, new AreaComparator()));
System.out.println(findMax(new Rectangle[] { new Rectangle(5, 6), new Rectangle(4, 5) }, new AreaComparator()));
}

