Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting on int field of object

 
Bud Tippins
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 607
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ...
 
Bud Tippins
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for your help. That worked.
 
Rob Spoor
Sheriff
Pie
Posts: 20510
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic