0

I have a class 'Point'. I want to sort an array of points, but I want to use 2 "compare" functions (I want to take 2 arrays, one with the points sorted by X and the other by Y). How can I make my class accept 2 comparing functions? Here's my code

static class Point implements Comparator<Point>{
    int x,y;
    int compareX(Point A , Point B){
        return A.x - B.x;
    }
    int compareY(Point A , Point B){
        return A.y - B.y;
    }
}
2
  • don't you already have 2 comparing functions? Commented Dec 2, 2016 at 13:00
  • The problem is I need to implement the 'compare' function which will be used in Arrays.sort(myArray) Commented Dec 2, 2016 at 13:01

1 Answer 1

2

Instead of having Point implement Comparator, have 2 Comparator constants which compare by x and y respectively.

static class Point {
  public static final Comparator<Point> X_COMPARATOR = Comparator.comparingInt(Point::getX);

  public static final Comparator<Point> Y_COMPARATOR = Comparator.comparingInt(Point::getY);
}
Sign up to request clarification or add additional context in comments.

7 Comments

I am not exactly sure how should I use this Comparators. This does not work: public Point sortByX(){ return Arrays.sort(this,X_COMPARATOR); }
@epanicafrate Point is not an array. Arrays.sort takes an Object[] as the first arg. docs.oracle.com/javase/8/docs/api/java/util/…
I meant Collections.sort, not Arrays.sort, my bad. But it still doesn't work.
Collections.sort takes a Collection as the first arg, not a Point. What is the exact error you ar getting.
@epanicafrate the error message says that S is of type Cmap.Point[]. So its not a Collection but an Array. So you should use Arrays.sort
|

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.