Reputation: 967
I am writing a function which uses generic parameters and converts them to their specific datatype adds them and returns the added value. I have done this for integer and double, but can't do the same for the string
I have tried using toString() function as well as String constructor but nothing seems to work!
public static <T extends Number> T add(T a, T b) {
if (a instanceof Integer) {
return (T) Integer.valueOf(a.intValue() + b.intValue());
} else if (a instanceof Double) {
return (T) Double.valueOf(b.doubleValue() + b.doubleValue());
} else if (a instanceof String) {
return (T) String.valueOf(a.toString() + b.toString());
}
}
I expect that it should return generic type argument but it throws couple of compile time errors:
java: incompatible types: T cannot be converted to java.lang.String
and
ava: incompatible types: java.lang.String cannot be converted to T
Upvotes: 1
Views: 7819
Reputation: 7792
Your Generic type T
is declared to extend Number
. String
does not extend Number
. And this is the root of your problem. Either your incoming parameters a
and b
extend number and thus may not be of type String
or your T
generic type may not extend Number
.
Another solution is to have your method as it is and not deal with String
type there and add another method that receives 2 String
params. However, note that adding 2 strings just concatenates them, so "2" + "4" will give you "24" which is probably not what you want/expect. If you expect Strings that represent numeric values you will need to write your own code to parse your String
params to Integer
or Long
or other implementation of Number
interface and then add them up
Upvotes: 2