在Java中取消装箱长 [英] Unboxing Long in java
问题描述
在某些代码中,我看到了这一点:
In some code I see this:
private void compute(Long a, Long b, Long c) {
long result = a-(b+c);
...
结果存储在原语中似乎有点奇怪strong> long 而不是与其操作数对应的 Long 对象。
It seems a bit strange that the result is stored in a primitive long instead of a Long object corresponding to its operands.
是否有任何理由将结果存储为基元?
Are there any reason that a result should be stored as a primitive?
推荐答案
结果存储在原始long而不是与其操作数对应的Long对象中似乎有点奇怪。
It seems a bit strange that the result is stored in a primitive long instead of a Long object corresponding to its operands.
不,奇怪是你可以使用 +
Long对象上的 -
运算符。在Java 5之前,这可能是语法错误。然后引入了自动装箱/拆箱。你在这段代码中看到的是 autounboxing :运算符需要初始化,因此编译器会自动在对象上插入对 longValue()
的调用。然后对原始 long
值执行算术,结果也是 long
,无需进一步转换即可存储关于变量。
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.
至于为什么代码执行此操作,真正的问题是为什么有人会使用 Long
键入而不是 long
。可能的原因:
As for why the code does this, the real question is why someone would use the Long
type instead of long
. Possible reasons:
- 这些值来自某些提供
Long
值的库/ API 。 - 这些值存储在集合中(
List
,Map
),不能保留原语。 - Sloppiness或货物崇拜节目 。
- 需要具有
null
值的能力,例如发出不可用或未初始化数据的信号。
- 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.
请注意 Long
能否持有 null
values表示计算(或更具体地说,编译器插入的 longValue()
调用)可能会因 NullPointerException
- 代码应该以某种方式处理的可能性。
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.
这篇关于在Java中取消装箱长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!