0

In sweep line algorithms, I use an array which sorts points by their x-coordinates, and a TreeSet that sorts points by their y-coordinates. Currently, I used two point classes to indicate which comparator to be used (i.e. whether to compare the x-coordinate or the y-coordinate). Is this possible with one point class but two compareTo functions? To illustrate, here's what I have. Apologies for the unprofessional terminology.

   public static class Point implements Comparable<Point>{
    int x; int y;
    public Point(int a, int b){
        this.x=a; this.y=b;
    }
    public int compareTo(Point other){
        if(this.x<other.x)return -1;
        if(this.x>other.x)return 1;
        if(this.y>other.y)return 1;
        return -1;
    }
}
public static class Point2 implements Comparable<Point2>{
    int x; int y;
    public Point2(int a, int b){
        this.x=a; this.y=b;
    }
    public int compareTo(Point2 other){
        if(this.y<other.y)return -1;
        if(this.y>other.y)return 1;
        if(this.x>other.x)return 1;
        return -1;
    }
}
hongsy
  • 1,498
  • 1
  • 27
  • 39
Kai
  • 101
  • 1
  • Note: I think using a treemap won't necessarily resolve the problem. – Kai Jan 24 '20 at 06:16
  • you can create a custom `Comparator`, then pass it in to the `TreeSet` constructor so that it can sort according to the specified comparator. see https://docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html#TreeSet-java.util.Comparator- – hongsy Jan 24 '20 at 06:44

1 Answers1

0

Both arrays and TreeSets allow sorting based on custom Comparators:

new TreeSet<>(new Comparator<T>() {
        @Override
        public int compare(T t1, T t2) {
            // your implementation here
        }
    });

Arrays.sort(arr, new Comparator<T>() {
        @Override
        public int compare(T t1, T t2) {
            // your implementation here
        }
    });
hongsy
  • 1,498
  • 1
  • 27
  • 39