Is it possible to write a generic +1 method for nu

2020-04-07 10:57发布

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?

7条回答
冷血范
2楼-- · 2020-04-07 11:30

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:

public Number plusOne(Number num) {
    return num + 1;
}
查看更多
登录 后发表回答