Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Newbie tries to use comparators... and fails.

 
Ian Taylor
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to understand how comparators work and to that end have created a simple program that will compare the integer variables in instances of a simple object. However, the comparator method fails to recognise the instance variables in the objects passed to it, giving a 'cannot find symbol' error at line 34 in Netbeans. I tried exactly the same program without the comparator implementation and it didn't give any errors, so I assume there is an aspect of the implementation/override aspect that I am goofing up. Go ahead and tell me what rookie error I am making this time Code below.

 
Tony Docherty
Bartender
Posts: 2960
59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your comparator class declaration should be:
 
Matthew Brown
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tony's right. You might be interested in what the effect of your mistake is. When you write:
It's actually using ObjectCreate as a generic type variable, not as a concrete type. So your class is the equivalent of this:
Now you can why that error occurs. As far as the compiler is concerned, T can be anything. So it has no idea whether it will have a objectScore field or not.
 
Ian Taylor
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see!

I need to understand generics much better. I got my original syntax from the example on this page

http://tutorials.jenkov.com/java-collections/sorting.html

Corrected and it works fine now, thanks both of you!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic