KhoaVo
KhoaVo

Reputation: 376

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

}
}

}

Hi, I'm trying to learn comparator by writing a small program to sort the list of rectangles. However, when I run this the output was the reverse of the original list instead of a sorted list. I don't quite understand comparator, I would really appreciate if you guys can provide some help, thanks.

Upvotes: 1

Views: 133

Answers (2)

Abhijeet Kale
Abhijeet Kale

Reputation: 1716

I think you should use some other calculation like "area" to compare it would be more meaningful comparison of rectangles: something like:

    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;

so this will sort on area of rectangle

Upvotes: 1

John3136
John3136

Reputation: 29266

Your comaparator is bad. It kind of handles equality but nothing else. Try something more like:

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

and so on.

Upvotes: 2

Related Questions