Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Define a Rectangle class that provides getLength and getWidth methods. Using the

ID: 3924033 • Letter: D

Question

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

Explanation / Answer

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()));

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote