简体   繁体   中英

Java/ Sort array which contain points

I have array with points: Point[] p = new Point[]

I want to sort it by x, and then by y. Meaning, If I have

Point A = (1, 2)
Point B = (2, 1)
Point C = (1, 3)
Point D = (2, 2)

After sorting, I will get: [(1,2), (1,3), (2,1), (2,2)]

I try to use Arrays.sort() , but point isn't comparable. There is an easy way to do that?

You can use Arrays.sort with a custom Comparer<Point> :

Arrays.sort(p, new Comparator<Point>() {
    int compare(Point a, Point b) {
        int xComp = Integer.compare(a.x, b.x);
        if(xComp == 0)
            return Integer.compare(a.y, b.y);
        else
            return xComp;
    }
});

Sidenotes:

  • If some of your Point objects may be null , you must handle this in compareTo .
  • If your Point is not an AWT point but your own class, you'd better let it implement Comparable .

Let Point implement the Comparable interface, and override its compareTo method to suit your needs.

    @Override
    public int compareTo(Point p) {
      if (this.x != p.x) {
        return Integer.compareTo(this.x, p.x);
      } else {
        return Integer.compareTo(this.y, p.y);
      }
    }

Read more: http://javarevisited.blogspot.com/2012/01/how-to-sort-arraylist-in-java-example.html#ixzz2S2i9k5V3

This requires editing the Point class. If that's not possible, see other answers for alternative solutions.

you can try (pseudo code).

   Arrays.sort(p, new Comparator<Point >() {
        public int compare(Point p1, Point p2) {

             //here operations and return
        }
    });

Since Point does not implement comparable you can create your own class for comparison:

public class Sorter implements Comparator 
{
  public int compare(Object o1, Object o2)
  {
    Point pointOne = (Point)o1;
    Point pointTwo = (Point)o2;
    return ((pointOne.getX()+pointOne.getY())+"").compareTo(((pointTwo.getX()+pointTwo.getY())+""));
  }
}

Then yo can use this Sorter class:

void mySortingFunc(Point[] points)
{
  Arrays.sort(points, new Sorter());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM