Since the Comparator class is part of the Java programming language, Android should do too. However, my experience with using them seem to indicate that it may not work all the time. Even I think it does not work in Android.

Has anyone else experienced this? Or even used it and worked? I made a Comparator class and ran it in Java’s runtime environment. It worked correctly. When I used the same class and sorted an ArrayList object in the Android emulator, it did not work. The sorting was different.

Now, I have no idea why. I always thought that there was something wrong with my custom Comparator class because the output in the Android emulator was always wrong. When I ran it in the JRE (since it was faster), the output was correct.

There should not be any rules to using comparators in the Android emulator. How they are used should be the same as when used in the Java Runtime Environment.

Please share your thoughts. Your inputs are highly appreciated and may help me know the limitations and what ifs when using a Comparator class in an Android emulator.

Comparing Dates using the Comparator class in Java is not the same as comparing Strings. Even if you convert the Date’s getTime() method to a Long object, using compareTo() on those two Long objects will not do the trick. However, you can make use of the long values right away.

Check out the code.

If your Vector object contains a set of custom class objects with a property of int and you want it to sort in ascending order, you can do it like this.

The getNumber() method contains the int value that will be used as basis to sort them in ascending order. To sort them in descending order, simply add a – (negative) sign after the keyword return.

Related Posts Plugin for WordPress, Blogger...