Is it possible to write a generic +1 method for numeric box types in Java?
- by polygenelubricants
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?