Search code examples
javagenericsprimitive

Java generic arithmetic


I'm trying to create some Java classes, that should work with either float or double numbers (for simulation purposes I am required to support both). The classes need to do some basic arithmetic and also require use of trigonometric functions (sin, cos, atan2).

I tried to do a generic approach. As Java does not allow primitive types in generics and MyClass<T extends Number> does indeed allow Double and Float, but makes basic arithmetic impossible, I build a wrapper class around Double and Float. But this approach fails, as soon as I need to instantiate a value in one of the generic classes.

Is there any clean way to support both float and double, without duplicating all the code for each type?


Solution

  • From experience, if you're doing hardcore numerical work in Java, it's better to stick to primitive types. This means that generics are a no-go for this type of work (but of course are perfectly fine for many other uses).

    Is there any clean way to support both float and double, without duplicating all the code for each type?

    You could implement the lower-precision method in terms of the higher-precision one:

    public static double calc(double x, double y) {
       // do the calculation and return double
    }
    
    public static float calc(float x, float y) {
       return (float)calc((double)x, (double)y);
    }