我用一种方法制作了数学运算的接口,计算,采用不同数量的参数
public interface MathOperation {
public <T extends Number> T calculate(T... args);
}
这个类还有一个简单的实现,但不起作用:
private class Sum implements MathOperation {
@Override
public <T extends Number> 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 <T>calculate(T...)
我想要实现的是一个简单的类,例如两个 Double 并返回 Double 。
有可能实现这一目标吗?
+
不能应用于以下类型extend Number
. new Integer(5) + new Integer(5)
由于自动装箱而起作用。您必须查看 args 的运行时类型并执行相应的操作。
大致如下:
private class Sum implements MathOperation {
@Override
public <T extends Number> T calculate(Class<T> clazz, T... args) {
if (clazz.equals(Integer.class))
{
return Integer.class.cast(args[0]) + Integer.class.cast(args[1]);
} else (....)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)