TreeSet矩形比较器

时间:2016-10-27 14:07:32

标签: java comparator treeset

快速提问,我在创建自己的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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

根据您的密码,您完全迷失了方向。这是比较类

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