I have a Rectangle class that in part of the code finds the area of the rectangle class using:
public double calculateArea() {return this.width * this.height;}
I have to create a second class called RectangleComparator and implement the comparator interface to compare two Rectangle objects according to area. The following code is what I have come up with for that:
import java.util.Comparator;
public class RectangleComparator implements Comparator<Rectangle> {
public int compare(Rectangle r1, Rectangle r2) {
double areaDifference = r1.calculateArea() - r2.calculateArea();
if (areaDifference != 0) {return (int) areaDifference;}
if (areaDifference < 0) {return -1;}
else if (areaDifference == 0) {return 0;}
else {return 1}
}
}
}
My final class I had to create was a RectangleSortTest class where the method creates a List containing five Rectangle objects, not in order by area. The method should print the list, displaying each rectangle's area. Then sort the list, and print the list again showing the list has been sorted by area. The following is what I have come up with:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class RectangleSortTest {
public static void main(String[] args) {
List<Rectangle> list = new ArrayList<>();
list.add(new Rectangle (12, 15));
list.add(new Rectangle (5, 2));
list.add(new Rectangle (19, 10));
list.add(new Rectangle (9, 5));
list.add(new Rectangle (6, 10));
System.out.printf("Unsorted list elements:%n%s%n", list);
Collections.sort(list, new RectangleComparator());
System.out.printf("Sorted list elements: %n%s%n", list);
}
}
Everything seems to run correctly but when I run the program and displays the following results:
Unsorted list elements: [Rectangle@7852e922, Rectangle@4e25154f, Rectangle@70dea4e, Rectangle@5c647e05, Rectangle@33909752] Sorted list elements: [Rectangle@4e25154f, Rectangle@5c647e05, Rectangle@33909752,Rectangle@7852e922, Rectangle@70dea4e]
If you look at it the objects seem to be sorting correctly but I cannot figure out why it will not display the area of each triangle instead of the results I got.
Any help would be appreciated.