繁体   English   中英

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

}
}

}

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

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

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;

所以这将对矩形区域进行排序

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM