That brings me to today’s questions. The code below for the Points class implements the compareTo() method. Now my manager kept insisting that there is something not right about it – but the code looks alright to me.
What do you folks think – are there any problems with the code below?
package com.twister;
import java.util.ArrayList;
import java.util.Collections;
public class Points implements Comparable<Points>{
int xCoordinate;
/*
* 1. Returns 0 if both points have same xCoordinate (say 3 & 3) - returns 3-3=0
* 2. Returns +ve if first point is on the
* right hand side of the second point (say 5, -3) - returns 5 - (-3) = 8
* 3. Returns -ve if first point is on the
* left hand side of the second point (say -5, 3) - returns (-5) - (3) = -8
*/
public int compareTo(Points p) {
return xCoordinate - p.xCoordinate;
};
public static void main(String[] args) {
ArrayList<Points> arrPoints = new ArrayList<Points>();
/* Add lots of points to the array list */
Collections.sort(arrPoints);
/*Print the sorted collection */
}
}
Got a view? Leave one here.