I am attempting to sort an ArrayList based on the value of a long present within each object. After following various examples around the internet, I have come up with the following code but it is not sorting as desired (it seems to truncate parts of the object).
public static Comparator<Customer> compareSIN =
new Comparator<Customer>() {
public int compare(Customer cust1, Customer other) {
String sin1 = "" + cust1.sin;
String sin2 = "" + other.sin;
return sin1.compareTo(sin2);
}
};
Please advise me on what I am doing missing in the first snippet of code that is preventing me from sorting the objects properly.
Thanks!
Anonymous User
05-Oct-2013You do not actually need to use a compareTo() method inside your own compareTo() method.
The compare to states that it must return 0 if they are equal and negative or positive numbers for non equality.
For this reason you can compare two longs by returning the one subtracted from the other.