Unboxing Long in java

前端 未结 9 1421
别跟我提以往
别跟我提以往 2021-01-15 16:44

In some code I see this:

private void compute(Long a, Long b, Long c) {
        long result = a-(b+c);
...
         


        
9条回答
  •  灰色年华
    2021-01-15 17:19

    It seems a bit strange that the result is stored in a primitive long instead of a Long object corresponding to its operands.

    No, what is "strange" is that you can use the + and - operators on Long objects. Before Java 5, this would have been a syntax error. Then autoboxing/unboxing was introduced. What you're seeing in this code is autounboxing: the operators require primtives, so the compiler automatically inserts a call to longValue() on the objects. The arithmetic is then performed on primitive long values, and the result is also a long that can be stored without further conversion on the variable.

    As for why the code does this, the real question is why someone would use the Long type instead of long. Possible reasons:

    • The values come from some library/API that delivers Long values.
    • The values are stored in collections (List, Map), which cannot hold primitives.
    • Sloppiness or cargo cult programming.
    • The ability to have null values is required, e.g. to signal unavailable or uninitialized data.

    Note that the ability of Long to hold null values means that the calculation (or more specifically, the longValue() calls inserted by the compiler) can fail with a NullPointerException - a possibility the code should deal with somehow.

提交回复
热议问题