Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: multiply generic Number without changing its type

Tags:

java

math

numbers

Is there a way in Java to implement this method?

public static <T extends Number> T doubleOf(T number){
    //I don't know...
}

Thanks

like image 765
rascio Avatar asked Mar 05 '26 18:03

rascio


1 Answers

As mentioned in other answers, there is no general solution. Beside others, the operation you want to implement may not be well defined for some Number subclasses. For instance, what is the multiple of AtomicInteger? Is it the same instance with a multiplied value? Or a new instance of AtomicInteger? Or a new plain Integer? Theoretically, there might be a subclass of Number that does not allow to create new instances freely.

You may test the input for some known subclasses and implement the operation for those. Something like this:

@SuppressWarnings("unchecked")
public static <N extends Number> N multiply(N number, int multiplier) {
    Class<? extends Number> cls = number.getClass();
    if (cls == Integer.class) {
        return (N) Integer.valueOf(number.intValue() * multiplier);
    }
    if (cls == Long.class) {
        return (N) Long.valueOf(number.longValue() * multiplier);
    }
    throw new UnsupportedOperationException("unknown class: " + cls);
}

I am afraid the suppression of warnings will be necessary, in some form.

like image 85
Marwin Avatar answered Mar 07 '26 07:03

Marwin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!