好的,你試圖實現的方法是不可能的。那麼,至少對我來說。我不知道如何解決它。但不管怎麼說,我會嘗試解釋爲什麼你得到錯誤:
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