I have class point that represents point in 2D and I want to sort these points once based on their x-coordinate and second based on their y coordinate. Since x and y are double values my code looks like this:
public static class Point{
int id;
public double x;
public double y;
Point(int id, double x, double y){
this.id = id;
this.x = x;
this.y = y;
}
public static Comparator<Point> xComparator = new Comparator<Point>(){
@Override
public int compare(Point t1, Point t2) {
// TODO Auto-generated method stub
if (t1.x > t2.x){
return 1;
}
if (t1.x < t2.x){
return -1;
}
else{
return 0;
}
}
};
public static Comparator<Point> yComparator = new Comparator<Point>(){
public int compare(Point t1, Point t2) {
// TODO Auto-generated method stub
if (t1.x > t2.x){
return 1;
}
if (t1.x < t2.x){
return -1;
}
else{
return 0;
}
}
};
}
Is this a good way for defining Comparator? Is there better solution for sorting based on x and on y coordinate? Is this the only way to deal with compare
method based on two double values?