Home > DeveloperSection > Forums > Sorting ArrayList Based on Value of Long using java
F Scott Fitzgerald
F Scott Fitzgerald

Total Post:29

Points:203
Posted on    October-05-2013 7:41 AM

 Java Java 
Ratings:


 1 Reply(s)
 943  View(s)
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!



Ida B Wells
Ida B Wells

Total Post:30

Points:210
Posted on    October-05-2013 8:59 AM

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;
}

Don't want to miss updates? Please click the below button!

Follow MindStick