1
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.

1
  • How do you consider Rectangle2D for comparison?Your comparator logic makes no sense to me.Pls put the source code of Rectangle2D also.You need to tweak your comparator logic first as I see you have provided default value with -1 ,meaning it mostly reverse the order unless your comparator logic works Commented Oct 5, 2015 at 4:49

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

don't forget to upvote if you find this answer useful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.