Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Mathematical operations on Objects  RSS feed

 
vijay kumarg
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can I do mathematical operations on Objects as similar to primitive types?
To do so what need to do?
Should I override equals(), hashCode() methods of that objects?
 
Ajay Singh
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
apart from hashCode and equals, you can implement
Comparable interface to have natural order comparison.
 
vijay kumarg
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Ajay,
Thanks for the reply.
Could You post some sample code.
I have a case where I need to add two Money objects.
 
Ajay Singh
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Comparable is only for natural ordering of the object. This example might be useful:
http://www.exampledepot.com/egs/java.lang/Sortable.html?l=rel

There is no interface in java that generalizes addition/subtraction/multiplication as they are specific to object-type. You need to
implement on your own.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess the feature you are looking for is operator overloading. Java doesn't have that feature - you will have to use standard method calls instead.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!