1

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?

1
  • 1
    Hint: Use Comparator or Comparable interface. Commented May 1, 2013 at 12:13

4 Answers 4

3

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Where I need to put this statement?
@TomAvni Wherever you tried Arrays.sort before. It's just an overload for arrays of non-Comparable objects.
1

you can try (pseudo code).

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

             //here operations and return
        }
    });

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.