This is NOT homework.
Part 1
Is it possible to write a generic method, something like this:
<T extends Number> T plusOne(T num) {
return num + 1; // DOESN'T COMPILE! How to fix???
}
Short of using a bunch of instanceof
and casts, is this possible?
Part 2
The following 3 methods compile:
Integer plusOne(Integer num) {
return num + 1;
}
Double plusOne(Double num) {
return num + 1;
}
Long plusOne(Long num) {
return num + 1;
}
Is it possible to write a generic version that bound T
to only Integer
, Double
, or Long
?
FWIW this isn't really a limitation of generics.
The + operator only works on primitives. The reason it works for Integer or Long is because of autoboxing/unboxing with their primitive types. Not all Number subclasses have a matching primitive type, but more importantly Number doesn't have a matching primitive type. So taking generics out of it completely, the following code would still be wrong: