This week's book giveaways are in the Scala and Android forums.
We're giving away four copies each of Machine Learning Systems: Designs that scale and Xamarin in Action: Creating native cross-platform mobile apps and have the authors on-line!
See this thread and this one for details.
Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Comparator for ArrayList not working  RSS feed

 
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,

 
Bartender
Posts: 4568
9
  • 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
 
Why is the word "abbreviation" so long? And this ad is so short?
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!