Is it possible to write a generic +1 method for numeric box types in Java?

后端 未结 7 2110
旧巷少年郎
旧巷少年郎 2021-01-18 15:56

This is NOT homework.

Part 1

Is it possible to write a generic method, something like this:



        
7条回答
  •  感动是毒
    2021-01-18 16:15

    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;
    }
    

提交回复
热议问题