BoostedMonkey BoostedMonkey - 1 month ago 30
Java Question

TreeSet Rectangle Comparator

Quick question, Im having a lot of trouble creating my own TreeSet rectangle comparator. Here is the code I have, but i'm extremely lost. I want to compare the areas of the rectangles and sort them in ascending order.

import java.util.TreeSet;
import java.awt.Rectangle;
import java.util.Comparator;

public class RectComp implements Comparator<Rectangle>
{
private double width;
private double height;

public RectComp(Comparator comp)
{
this.width = width;
this.height = height;
}

public double getArea()
{
return width * height;
}

public int compare(Rectangle r1, Rectangle r2)
{
double diff = r1.getArea() - r2.getArea();

if (diff < 0)
return -1;
else if (diff == 0)
return 0;
else
return 1;
}

public static void main(String[] args)
{
TreeSet<Rectangle> set = new TreeSet<>(new RectComp());

set.add(new Rectangle(1, 10));
set.add(new Rectangle(10, 1));
set.add(new Rectangle(5, 3));
set.add(new Rectangle(5, 2));
set.add(new Rectangle(5, 1));

for (Rectangle r : set) {
System.out.println(r);
}
}
}

Answer

You are completely lost according to your codes. Here is the Compare Class

    public class RectComp implements Comparator<Rectangle>{

        public int compare(Rectangle r1, Rectangle r2) {

            double diff = r1.getHight()*r1.getWidth() - r2.getHight()*r2.getWidth();
            if(diff < 0)
                return -1;
            else if (diff == 0)
                return 0;
            else return 1;
        }
}
Comments