File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Comparator for ArrayList not working Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Comparator for ArrayList not working" Watch "Comparator for ArrayList not working" New topic

Comparator for ArrayList not working

Nigel Shrin
Ranch Hand

Joined: May 18, 2009
Posts: 140
I have a class that contains a field, ArrayList<Long> that will hold a quantity of between one and four numbers. I want to sort the contents in descending order to then remove duplicates. I have created a comparator object and passed it to Collections.Sort but it errors with the error below. I have seen examples extremely similar using Integer instead of Long that work, which work "because Integer implements the Comparable interface", well Long does also, so I don't understand what the error means?

The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (Long, FourSqResComparator)



Many thanks,

Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

Look at your result variables. You've got more than one, and they have completely different meanings. That's often going to lead to problems, as it does on line 22 when the compiler's using a different variable to the one you think it's using. Rename the variables to something more meaningful and that should fix your problem.

Also, though, there's an easier way of sorting in reverse natural order. You don't need to create your own Comparator, as the java.util.Collections#reverseOrder() method will give you one for free.
Nigel Shrin
Ranch Hand

Joined: May 18, 2009
Posts: 140
Hi Matthew, thanks for the suggestion, I am actually in the middle of trying to implement that right now. I was trying to perform two functions in one, and the argument wasn't suitable for the sort.

I'll repost shortly and let you know how I got on!
thanks for the reply

Nigel Shrin
Ranch Hand

Joined: May 18, 2009
Posts: 140
Hi Matthew,

I created a new method to return the whole ArrayList<Long> then in the calling program I was able to add:

which has worked a treat

many thanks for your help
I agree. Here's the link:
subject: Comparator for ArrayList not working
It's not a secret anymore!