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

So, I want to sort an array of points using the built-in sort method defined by the coordinate, for example x. How can i do this? Here is 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 it and use it. An example would be great.

Thank.

+3
source share
2 answers

Pointnot Comparable, so you will need to write your own comparator and pass it on call Arrays.sort. Fortunately, this is not too complicated:

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());
+8
source

You can also use Apache Commons Bean Comparator

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

-

import org.apache.commons.beanutils.BeanComparator;

Arrays.sort(A, new BeanComparator("x"));
+2

Source: https://habr.com/ru/post/1750860/


All Articles