Java generic arithmetic

橙三吉。 提交于 2021-01-27 06:32:13

问题


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?


回答1:


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);
}



回答2:


Maybe this is what you are looking for?

class MyClass<T extends Number> {
    T add(T t1, T t2) {
        if (t1 instanceof Double) {
            return (T) Double.valueOf((t1.doubleValue() + t2.doubleValue()));
        } else if (t1 instanceof Float) {
            return (T) Float.valueOf(((t1.floatValue() + t2.floatValue())));
        } else if (t1 instanceof Integer) {
            return (T) Integer.valueOf(((t1.intValue() + t2.intValue())));
        }
        // you can add all types or throw an exception
        throw new IllegalArgumentException();
    }

    public static void main(String[] args) {
        MyClass<Double> mc = new MyClass<Double>();
        mc.add(1.0, 1.1);
    }
}


来源:https://stackoverflow.com/questions/13911188/java-generic-arithmetic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!