java.lang.Number doesn't implement “+” or any other operators?

后端 未结 7 1667
梦毁少年i
梦毁少年i 2020-12-17 19:56

I\'m creating a class which is supposed to be able to be used with an array of any type of number (float, int, etc), so here is one method I have:

// T exten         


        
相关标签:
7条回答
  • 2020-12-17 20:36

    You need to convert your numbers to primitive types, and then the arithmetic operators will work. You will notice that Number does have doubleValue, intValue, etc....

    or alternatively, you can convert to BigDecimal, and use the arithmetic methods defined on that class (not +,-, etc, but add, multiply, etc....). This method will be more accurate (if you need the best accuracy, use BigDecimal) since floats and doubles only represent a discrete set of numeric values. Keep in mind that BigDecimals are immutable, so you always need to assign the result of an operation to a reference.

    0 讨论(0)
提交回复
热议问题