TreeSet 矩形比较器

TreeSet Rectangle Comparator

快速提问,我在创建自己的 TreeSet 矩形比较器时遇到了很多麻烦。这是我的代码,但我非常迷茫。我想比较矩形的面积并按升序排序。

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);
        }
    }
}

根据你的代码,你完全迷路了。这是比较 Class

    public class RectComp implements Comparator<Rectangle>{

        public int compare(Rectangle r1, Rectangle r2) {

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