Jemar Jones
Jemar Jones

Reputation: 1645

Arithmetic with generic Numbers

So I have to accept a generic type T, which will be a wrapper class for one of the numeric primitives, and do some arithmetic with it. I thought this would be trivial because of autoboxing and unboxing:

T newval = val1*val2;

(Where val1 and val2 are already variables of type T with appropriate values in them.)

But it turns out that Java won't unbox values if it doesn't know the type explicitly at compile time. I also thought that I could just use the multiply method that each of the Number subclasses (that I intend to use) have within them. So I declared my class with:

public class SomeClass<T extends Number> {
    // ...
}

and then:

T newval = val1.multiiply(val2);

But that doesn't work because I guess not all subclass' of Number are required (Why don't they use an interface for this?) to have that method (yet all the ones that I want to use DO.)

I've seen some similar questions but they all resulted in OP being told to just not use generics, yet I am required to use generics for the work I'm doing, otherwise the entire thing is worthless. Can anybody think of a solution that will work for me?

EDIT: Okay so he got back to me and clarified what was meant, it's different enough that my question is no longer relevant to what i'm doing. Thanks guys.

Upvotes: 0

Views: 580

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

The various arithmetic operators can only be applied to values of types that are convertible to primitive types. There is no way to express that requirement with generics. Therefore generics are not suited for this task.

For generics methods, instead provide overloads for the numeric primitive types. For generic classes, provide subclasses that use a specific numeric type.

class NumericCalculator<T> {
    public void calculate(T one, T two) {
        T result = one * two; // compiler error
    }
}

class LongCalculator extends NumericCalculator<Long> {
    public void calculate(Long one, Long two) {
        Long result = one * two; // yes
    }
}

The implementation that uses the operators will have to be in the subclasses which know the actual type.

Upvotes: 5

Related Questions