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!
From the title I assume
Customer.sinis along– and the problem is you are trying to compare them asStrings rather then by their numeric value.(Example: 10000 is lexicographically smaller then 2 – so using
Strings here is the fault)You should use
Long.compare()(Assuming java 7):