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

后端 未结 7 2033
旧巷少年郎
旧巷少年郎 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:17

    The problem here is that your code must unbox the object, operate on the primitive, and then rebox it. Java really can't do that because by the time the code is compiled, it doesn't know what the type is any more, so it doesn't know how to unbox.

    The value of Java generics is really to preserve type safety, i.e. the compiler knows the real class and will prevent illegal assignments. The compiler will NOT generate different code depending on the type: it WON'T say "oh, that's an integer, so I need to generate an integer add here, versus that one's a String, so the plus sign really means string concatenation". It's really quite different from C++ templates, if that's what you're thinking of.

    The only way you could make this work would be if there was a plusOne function defined for Number, which there isn't.

提交回复
热议问题