collections.sort 没有对 arraylist 进行排序

collections.sort did not sort arraylist

public class RectangleComparator implements Comparator<Rectangle2D>  {

double x1;
double x2;
double y1;
double y2;
double w1;
double w2;
double h1;
double h2;

@Override
public int compare(Rectangle2D o1, Rectangle2D o2) {
    x1 = o1.getX();
    x2 = o2.getX();
    y1 = o1.getY();
    y2 = o2.getY();
    w1 = o1.getWidth();
    w2 = o2.getWidth();
    h1 = o1.getHeight();
    h2 = o2.getHeight();
    int result = -1;
    if (x1 == x2)
        result = 0;
    if (result == 0)
    {
        if (y1 == y2)
            result = 0;
    }
    if (result == 0)
    {
        if (w1 == w2)
            result = 0;
    }
    if (result == 0)
    {
        if (h1 == h2)
            result = 0;
    }
     return result;
}

public class RectangleTester {

public static void main(String[] args)
{
    ArrayList <Rectangle2D> rect = new ArrayList<Rectangle2D>();
    rect.add(new Rectangle2D.Double(20,15,14, 10));
    rect.add(new Rectangle2D.Double(20,16,11, 5));
    rect.add(new Rectangle2D.Double(17,28,90, 100));
    rect.add(new Rectangle2D.Double(15,9,60, 75));
    rect.add(new Rectangle2D.Double(41,56,21, 19));


        Collections.sort(rect, new RectangleComparator());
        for (Rectangle2D temp : rect)
            System.out.println(temp.toString());

}
}

}

您好,我正在尝试通过编写一个小程序对矩形列表进行排序来学习比较器。但是,当我 运行 时,输出是原始列表的反向而不是排序列表。 comparator我不是很懂,如果有大佬能帮忙指点一下,谢谢了。

你的比较器不好。它有点处理平等,但没有别的。 尝试更像:

result = x2-x1;
if (result == 0) {
    result = y2-y1;
    if (result == 0) {
        result = w2-w1;

等等。

我认为你应该使用其他一些计算,如 "area" 来比较矩形比较更有意义: 类似于:

    area1 = o1.getWidth() * o1.getHeight();
    area2 = o2.getWidth() * o2.getHeight();
    if (area1 == area2)
        return 0;
    else if (area > area2)
        return -1;
    else if (area1 < area2)
        return 1;

所以这将按矩形区域排序