The comparator is the proper way to go. You could sort you arrays of x and y values so that the ending array of Points is sorted, but I think that making your point class implement the Comparable interface is better and less error prone.
class Point implements Comparable<Point>{
public float x;
public float y;
@Override
public int compareTo(Point o) {
if(this.x>o.x){
return 1;
}else if(this.x==o.x){
return 0;
}else{
return -1;
}
}
}
Then you can just call
Arrays.sort(graphPoints);
to sort it.
Switching the 1 and -1 return values will switch whether it sorts in Ascending or Descending order.
Explanation
What this does is when you call the Arrays.sort
method, it will compare every point in the array by using the compareTo method. If compare to returns a 1, the sort method knows that point is considered greater than the other one it compared. If its 0, they are equal. And if its -1, then it is less. This the standard way to go and makes it easy to sort an Array without having to write the sorting code yourself, which would probably be messy and inefficient.
Further, it makes it easy to change the behavior of the sorting simply by changing your compareTo method. You can change whether it is in ascending or descending order, as well as what you are sorting by. For example, if you want to you can easily change whether it sorts by the x or the y value just by changing compareTo in one place.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…