I am trying to set up my rectangle comparator class to print
I am trying to set up my rectangle comparator class to print out the rectangles in ascending order. I am having an error at the line where I make the tree set. Below is my code. I feel like I am really close to answering this, but I am not sure how to fix it. I asked a similar question earlier but could not figure out how to edit my question to update what I have. Please Help!
import java.awt.Rectangle;
import java.util.Comparator;
import java.util.TreeSet;
public class RComp
{
public static void main(String[]args)
{
TreeSet <Rectangle > Rset = new TreeSet <>(new RectangleComp ());
Rset.add(new Rectangle (2, 7));
Rset.add(new Rectangle (8, 3));
Rset.add(new Rectangle (6, 10));
Rset.add(new Rectangle (4, 2));
Rset.add(new Rectangle (8, 6));
for (Rectangle r : Rset)
{
System.out.println(r);
}
}
class RectangleComp 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;
}
}
}
}
Solution
Program:
import java.awt.Rectangle;
import java.util.Comparator;
import java.util.TreeSet;
public class RComp
{
public static void main(String[]args)
{
TreeSet <Rectangle > Rset =new TreeSet <>(new RectangleComp());
Rset.add(new Rectangle (2, 7));
Rset.add(new Rectangle (8, 3));
Rset.add(new Rectangle (6, 10));
Rset.add(new Rectangle (4, 2));
Rset.add(new Rectangle (8, 6));
for (Rectangle r : Rset)
{
System.out.println(r);
}
}
public static class RectangleComp implements Comparator<Rectangle >
// Only static variables references static context
{
@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;
}
}
}
}
Output:
java.awt.Rectangle[x=0,y=0,width=4,height=2]
java.awt.Rectangle[x=0,y=0,width=2,height=7]
java.awt.Rectangle[x=0,y=0,width=8,height=3]
java.awt.Rectangle[x=0,y=0,width=8,height=6]
java.awt.Rectangle[x=0,y=0,width=6,height=10]

