I want to perform basic arithmetic operations like addition, subtraction, multiplication and division using only one generic method per operation for wrapper types like Integer
, Float
, Double
... (excluding BigDecimal
and BigInteger
).
I have tried to do something like the following (for addition) using a generic class.
public final class GenericClass<E extends Number> {
public E add(E x, E y) {
return x + y; // Compile-time error
}
}
It issues a compile-time error,
operator + cannot be applied to E,E
Is there a way to use such a generic version to achieve such operations?
2.1. 1 Numerical Calculations. The basic arithmetic operations (addition, subtraction, multiplication, division, and exponentiation) are performed in the natural way with Mathematica.
Addition, subtraction, multiplication, and division constitute the four basic arithmetic operations. There has been considerable behavioral research on the cognitive processes associated with these operations over the past several decades.
…how to perform the four arithmetic operations of addition, subtraction, multiplication, and division.
No, there isn't a way to do this, or else it would be built into Java. The type system isn't strong enough to express this sort of thing.
No, you can't do that because the + operator is not part of the Number class. What you can do is to create an abstract base class and extends from it:
static void test() {
MyInteger my = new MyInteger();
Integer i = 1, j = 2, k;
k = my.add(i, j);
System.out.println(k);
}
static public abstract class GenericClass<E extends Number> {
public abstract E add(E x, E y);
}
static public class MyInteger extends GenericClass<Integer> {
@Override
public Integer add(Integer x, Integer y) {
return x + y;
}
}
(I made these classes static in order to facilitate the testing but you can remove this modifier.)
You could also add an abstract function that will take and return parameters and return value of type Number and override it and the subclasses but the required casting for the return value will defeat its usefulness.
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