Tom Avni
Tom Avni

Reputation: 149

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?

Upvotes: 1

Views: 5559

Answers (4)

Matthias Meid
Matthias Meid

Reputation: 12523

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.

Upvotes: 3

user1697575
user1697575

Reputation: 2848

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

Upvotes: 0

Victor Sand
Victor Sand

Reputation: 2340

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.

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 122008

you can try (pseudo code).

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

             //here operations and return
        }
    });

Upvotes: 1

Related Questions