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

前端 未结 2 495
遥遥无期
遥遥无期 2021-01-21 01:03

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 Po         


        
2条回答
  •  星月不相逢
    2021-01-21 01:46

    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 {
        int compare(Point a, Point b) {
            return (a.x < b.x) ? -1 : (a.x > b.x) ? 1 : 0;
        }
    }
    
    Arrays.sort(A, new PointCmp());
    

提交回复
热议问题