通用类型扩展数,计算
我用一种方法建立了数学运算的接口,计算,得到了不同数量的参数
public interface MathOperation { public T calculate(T... args); }
还有这个类的简单实现,它不起作用:
private class Sum implements MathOperation { @Override public T calculate(T... args) { return args[0] + args[1]; } }
问题是:
bad operand types for binary operator '+' first type: T second type: T where T is a type-variable: T extends Number declared in method calculate(T...)
我想要实现的是一个简单的类,例如两个双打并返回Double。
是否有可能实现这一目标?
+
不能应用于extend Number
类型。 new Integer(5) + new Integer(5)
因autoboxing而起作用。 您将不得不查看args的运行时类型并相应地执行操作。
有点像:
private class Sum implements MathOperation { @Override public T calculate(Class clazz, T... args) { if (clazz.equals(Integer.class)) { return Integer.class.cast(args[0]) + Integer.class.cast(args[1]); } else (....) } }
您可以测试运行时类型,如其他答案中所示。 或者您可以尝试不同的设计:创建一个作为工厂的抽象类:
interface MathContext { ... T valueOf(double d); T valueOf(int i); T add (T... args); }
您要使用的类型的具体类:
DoubleContext implements MathContext { ... Double valueOf(int i) { return i; } Double valueOf(double d) { return d; } Double add(Double... args) { Double res = 0; for (Double arg: args) { res += arg; } return res; } }
现在,您可以使用该类实现MathOperation。 但是,它不再需要了。