好的,你试图实现的方法是不可能的。那么,至少对我来说。我不知道如何解决它。但不管怎么说,我会尝试解释为什么你得到错误:
The operator + is undefined for the argument type(s) T, T
这只是意味着,什么是一个+
做一个类型T
?
嗯,这是有道理的,当我们试图做这样的事情:
Calculadora<Integer> c = new Calculadora<Integer>();
因为Integer
可以转换为int
和编译器确切地知道如何与int
正确添加int
?
但由于T
可以是任何类型的,如果我们这样做:
Calculadora<Cat> c = new Calculadora<Cat>();
显然,我们不知道到底如何,你将添加一个Cat
与另一Cat
。这就是为什么编译器给你的错误,它告诉你,我不知道如何将这个类型加在一起。我只能添加数字和字符串。
希望这会有所帮助。 :)
编辑2:
嗯,我看到它,如果你真的需要做这样的事情,你将不得不改变你的类和方法声明一点的方式,东西如:
//Limit only the Generics to subtypes of Number
class Calculadora<T extends Number> {
//Return a specific type (Can be Double, Float, Long, etc.)
Integer suma(T a, T b) {
//Change this based on your return type (Can be double, float, long, etc.)
int sum = 0;
if (a instanceof Number && b instanceof Number) {
//Change this accordingly too (Can be doubleValue(), floatValue(), longValue(), etc.)
sum = a.intValue() + b.intValue();
}
return sum;
}
}
这仅限于Integer
。如果需要,您可以将其更改为Number
的任何子类型。
这看起来不像是那个问题的重复。目标是增加,但是尝试的技术和伴随而来的问题完全不同。 – amalloy 2014-09-24 08:03:23