views:

57

answers:

2

Hi,

So I wanna sort an array of Points using the built in sorting method, by a specific coordinate, say x. How can I do this? Heres a sample code:

Point A[] = new Point[10];
// ... Initialize etc.
Arrays.sort(A, x-coordinate);

Is there a built-in comparator for x-coordinates in Point Class? If not, how can I create one and use it. An example would be great.

Thanks.

+4  A: 

Point isn't Comparable so you'll need to write your own comparator and pass it in when calling Arrays.sort. Luckily, that's not too hard:

class PointCmp implements Comparator<Point> {
    int compare(Point a, Point b) {
        return (a.x < b.x) ? -1 : (a.x > b.x) ? 1 : 0;
    }
}

Arrays.sort(A, new PointCmp());
Donal Fellows
Please use any two of <, ==, >. People use subtraction all the time for this. One of them will have a subtraction that overflows, and boom.
Dimitris Andreou
Why? If you're working with points on a GUI then it's fine. Or you've got a physical screen more than 2G pixels across (to allow for signedness issues). If that's true, I hate you!
Donal Fellows
It's a "cute programmer trick" to use subtraction instead of <, >, ==. Makes your code harder to read and introduces the possibility of bugs for no real benefit. If you were on my project and wrote this, I would tell you to try again... :)
bwawok
OTOH, if you're going to work with `Point2D.Double` or `Point2D.Float` then you'll want to do it the way I've updated my answer to.
Donal Fellows
A: 

You can also use Apache Commons Bean Comparator

http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/BeanComparator.html

And then do something like

import org.apache.commons.beanutils.BeanComparator;

Arrays.sort(A, new BeanComparator("x"));
bwawok
really, this is the best way you can solve this problem, add megs of crappy "commons" crap dependencies to your project to compare to objects?
fuzzy lollipop
How many projects don't already have apache commons? I haven't worked on a big project that didn't have it as a dependency somewhere down the maven chain
bwawok