I am trying to create a generic class in Java that will perform operations on numbers. In the following example, addition, as follows:
public class Example <T extends Number> { public T add(T a, T b){ return a + b; } }
Forgive my naivety as I am relatively new to Java Generics. This code fails to compile with the error:
The operator + is undefined for the argument type(s) T, T
I thought that with the addition of "extends Number" the code would compile. Is it possible to do this Java or will I have to create overridden methods for each Number type?
Definition. The arithmetic operators perform addition, subtraction, multiplication, division, exponentiation, and modulus operations.
Basic Arithmetic OperationsAddition (Finding the Sum; '+') Subtraction (Finding the difference; '-') Multiplication (Finding the product; '×' ) Division (Finding the quotient; '÷')
Instead of using operators in mathematical expressions, you can perform basic arithmetic operations with the keywords ADD, SUBTRACT, MULTIPLY, and DIVIDE. p = n + m. ADD n TO m. P = m - n.
The four arithmetic operations - addition, subtraction, multiplication, and division represents: Additions represent the sum of two values. Subtraction represents the difference between two numbers.
Number does not have a + operator associated with it, nor can it since there is no operator overloading.
It would be nice though.
Basically, you are asking java to autobox a descedant of Number which happens to include Integer, Float and Double, that could be autoboxed and have a plus operator applied, however, there could be any number of other unknown descendants of Number that cannot be autoboxed, and this cannot be known until runtime. (Damn erasure)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With