I am building on top of my previous program which used sorting algorithms to sort through integers in an array.
I'm now tasked with creating an ArrayList of Rectangles, creating a Rectangle class which extends the Comparable interface, and implementing generics in my sorting methods.
In the end, the program needs to calculate and sort through the given area values of 10 different Rectangles.
The problem I am having is, I'm not sure how to modify my sorting algorithms to implement generics, and use the compareTo
/getArea
methods I have created in the Rectangle class.
I am fairly new to all of these concepts so my understanding is limited.
Here is a snippet of how I have created my ArrayList of 10 Rectangles (in descending values):
public static void main(String[] args) {
ArrayList<Rectangle> list = new ArrayList<>();
for (int i=10;i>=1;i--) {
Rectangle rectangle = new Rectangle((i+5)*2,(i+7)*6);
list.add(rectangle);
}
...
}
This is my Rectangle class which extends the Comparable interface and has the overridden compareTo method:
class Rectangle implements Comparable<Rectangle> {
double width=1;
double height=1;
public Rectangle() { }
public Rectangle(double recWidth, double recHeight) {
this.width = recWidth;
this.height = recHeight;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getArea() {
return width * height;
}
@Override
public int compareTo(Rectangle r) {
if (getArea() > r.getArea()) {
return 1;
}
else if (getArea()<r.getArea()) {
return -1;
}
else {
return 0;
}
}
...
}
And this is my current bubble sort method which is no longer functioning.
public static <R extends Comparable <Rectangle>> void bubbleSort(ArrayList<Rectangle> list) {
for (int k = 1; k < list.size();k++) {
for (int i = 0; i <list.size()-k; i++) {
R elem = list.getArea();
R elem2 = list.getArea(i+1);
if (elem.compareTo(elem2) >= 1) {
R temp = list.get(i);
list.set(i, list.get(i+1));
list.set(i+1, temp);
}
}
printList(list);
}
}
Error message:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method getArea() is undefined for the type ArrayList<Rectangle>
The method getArea(int) is undefined for the type ArrayList<Rectangle>
The method compareTo(Rectangle) in the type Comparable<Rectangle> is not applicable for the arguments (R)
Type mismatch: cannot convert from Rectangle to R
The method set(int, Rectangle) in the type ArrayList<Rectangle> is not applicable for the arguments (int, R)
Again, I'd like my bubble sort method to obtain the area of each Rectangle being compared and sort them accordingly.
Any guidance or assistance is appreciated. Thanks!