| Author |
Sorting on int field of object
|
Bud Tippins
Ranch Hand
Joined: Jan 28, 2011
Posts: 52
|
|
The following code works fine for sorting on the title (String) field of the object Song. But if I want to sort on the intRating (int) field and I change line #53 to "return intRating.compareTo(s.getIntRating());" I get and error in NetBeans saying "int cannot be dereferenced." How can I go about sorting on this int field?
Thank you for your help.
|
 |
Tom Reilly
Rancher
Joined: Jun 01, 2010
Posts: 618
|
|
|
intRating is an int, which is a primitive type. The C# language allows you to call methods on primitive types but Java does not. You need to change your code to use the syntax that compares two primitive types.
|
 |
Saifuddin Merchant
Ranch Hand
Joined: Feb 08, 2009
Posts: 576
|
|
Tom Reilly wrote:intRating is an int, which is a primitive type. The C# language allows you to call methods on primitive types but Java does not. You need to change your code to use the syntax that compares two primitive types.
Or change the int to an wrapped Integer type ...
|
Cheers - Sam.
Twisters - The new age Java Quiz || My Blog
|
 |
Bud Tippins
Ranch Hand
Joined: Jan 28, 2011
Posts: 52
|
|
|
Thank you for your help. That worked.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
Tom Reilly wrote:intRating is an int, which is a primitive type. The C# language allows you to call methods on primitive types but Java does not. You need to change your code to use the syntax that compares two primitive types.
Just a warning: don't use simple subtraction to compare the two. That will give you problems when overflow occurs. Consider the following example:
That's why I always use < and >, usually in a nested terniary operator for brevity:
After all, the comparison only cares if the value is 0, negative or positive. The actual value does not matter.
Of course, since the result of any mathematical operation is never smaller than int, you can simply use subtraction for bytes, chars and shorts:
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: Sorting on int field of object
|
|
|