1I am trying to write a progam using a java tree set 2The se
1.I am trying to write a progam using a java tree set.
2.The set must contain java.awt.Rectangle objects and I need to make a custom comparator to sort them by area in ascending order.
3.Below is what the main method for the comparator should look like.
4.The comparator in it is called RectangularComp. I am needing help on making a custom comparator that can sort them in ascending order.
public static void main(String[]args]
{
TreeSet <Rectangle > Rset = new TreeSet <>(new RectangularComp ());
set.add(new Rectangle (2, 7));
set.add(new Rectangle (8, 3));
set.add(new Rectangle (6, 10));
set.add(new Rectangle (4, 2));
set.add(new Rectangle (8, 6));
for (Rectangle r : Rset)
{
System.out.println(r);
}
}
Solution
Hi,
1)you can add a new class to your program with the name RectangularComp besides of the existing class having main method and your code.
2)For the new RectangularComp class you have to implement An existing comparator interface
3)Then you can override the existing compare function of the the comparator interface
Please see the below code:
class RectangularComp implements Comparator<Rectangle >{
@Override
public int compare(Rectangle r1, Rectangle r2) {
double area1 = r1.getWidth()*r1.getHeight();
double area2 = r2.getWidth()*r2.getHeight();
if(area1 > area2){
return 1;
} else {
return -1;
}
}
}
I have used the inbuild methods of Rectangle class of java.awt.Rectangle both getWidth and getHeight()\\
If you want full code for the program please give the entire program code and get back to me if you have any queries
Thank you

