Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a generic class to perform basic arithmetic operations

Tags:

java

generics

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?

like image 849
Tiny Avatar asked Dec 26 '12 21:12

Tiny


People also ask

What is used to perform basic arithmetic operations?

2.1. 1 Numerical Calculations. The basic arithmetic operations (addition, subtraction, multiplication, division, and exponentiation) are performed in the natural way with Mathematica.

Can you perform the four basic arithmetic operations?

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.

What are the four basic arithmetic operation used in mathematics?

…how to perform the four arithmetic operations of addition, subtraction, multiplication, and division.


2 Answers

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.

like image 177
Louis Wasserman Avatar answered Oct 19 '22 11:10

Louis Wasserman


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.

like image 6
SylvainL Avatar answered Oct 19 '22 11:10

SylvainL