| Author |
Newbie tries to use comparators... and fails.
|
Ian Taylor
Greenhorn
Joined: Sep 03, 2012
Posts: 21
|
|
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
Joined: Aug 07, 2007
Posts: 1150
|
|
Your comparator class declaration should be:
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3786
|
|
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
Joined: Sep 03, 2012
Posts: 21
|
|
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!
|
 |
 |
|
|
subject: Newbie tries to use comparators... and fails.
|
|
|