collections.sort没有排序arraylist

时间:2015-10-05 04:44:19

标签: java sorting comparator

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

}
}

}

嗨,我试图通过编写一个小程序来对矩形列表进行排序来学习比较器。但是,当我运行它时,输出与原始列表相反,而不是排序列表。我不太了解比较器,如果你们能提供一些帮助我真的很感激,谢谢。

2 个答案:

答案 0 :(得分:2)

你的同事很糟糕。它有点处理平等,但没有别的。 尝试更像:

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

等等。

答案 1 :(得分:1)

我认为你应该使用其他一些计算,如&#34; area&#34;比较它将是更有意义的矩形比较: 类似的东西:

    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;

所以这将对矩形区域

进行排序