jNoob
jNoob

Reputation: 51

How to sort an array of objects(Points) in Java?

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.

Upvotes: 3

Views: 5443

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137707

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

Upvotes: 8

bwawok
bwawok

Reputation: 15357

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

Upvotes: 2

Related Questions