• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparator for ArrayList not working

 
Nigel Shrin
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
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?

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


CLASS:




MY COMPARATOR:




Many thanks,

 
Matthew Brown
Bartender
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic