3

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.

2 Answers 2

8

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());
Sign up to request clarification or add additional context in comments.

5 Comments

Please use any two of <, ==, >. People use subtraction all the time for this. One of them will have a subtraction that overflows, and boom.
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!
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... :)
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.
Alternatively, you could do Double.compare(a.x, b.x). Shorter, and near impossible to get wrong.
2

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

2 Comments

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
@JarrodRoberson Chill out, it shows an interesting way of abstracting a comparator by a field, OP can write one of his own if they choose

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.