SORTING ARRAYLIST BASED ON VALUE OF LONG USING JAVA

F Scott Fitzgerald

Total Post:29

Points:203
Posted by  F Scott Fitzgerald
Java 
 1297  View(s)
Ratings:
Rate this:

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!

  1. Ida B Wells

    Post:30

    Points:210
    Re: Sorting ArrayList Based on Value of Long using java

    You 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.

    public int compare(Customer cust1, Customer other) {
               return cust1.sin - other.sin;
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!