java 装箱的值被取消装箱,然后立即重新装箱
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12066682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
A boxed value is unboxed and then immediately reboxed
提问by Srinivasan
I am getting the Findugs error "A boxed value is unboxed and then immediately reboxed".
我收到 Findugs 错误“一个装箱的值被取消装箱,然后立即重新装箱”。
This is the Code:
这是代码:
Employee emp = new Employee()
Long lmt = 123L;
emp.setLimit(Long.valueOf(lmt));
In this, Employee limit
field is of type Long
. Could you please let me know what is the error?
在此, Employeelimit
字段的类型为Long
。你能告诉我是什么错误吗?
回答by Peter Butkovic
The problem is that you're converting Long
-> long
-> Long
.
问题是您正在转换Long
-> long
-> Long
。
So in the background:
所以在后台:
Long.valueOf(lmt)
convertsLong
tolong
emp.setLimit(<long>);
convertslong
toLong
again
Long.valueOf(lmt)
转换Long
为long
emp.setLimit(<long>);
再次转换long
为Long
As of Java 5 autoboxing happens => your code should look like this:
从 Java 5 自动装箱开始 => 你的代码应该是这样的:
Employee emp = new Employee()
Long lmt = 123L;
emp.setLimit(lmt);
or even:
甚至:
Employee emp = new Employee()
long lmt = 123L;
emp.setLimit(lmt);
回答by jpkrohling
That happens because Long.valueOf(long)
will unbox your lmt
from Long
to long
, just to get a Long
again. As you said that limit
is a Long
, you don't need to use Long.valueOf
, just use the var:
发生这种情况是因为Long.valueOf(long)
会将您的lmt
from拆箱Long
到long
,只是为了Long
再次获得。至于你说的那limit
是Long
,你不需要使用Long.valueOf
,只要使用var:
emp.setLimit(lmt);
回答by Andreas Dolk
emp.setLimit(Long.valueOf(lmt));
Long.valueOf
takes a long
value, but you pass a Long
value -- mandating unboxing. Immediately afterward, however, Long.valueOf
re-boxes the value and the expression evaluates to a Long
again. FindBugs detects the unnecessary conversion chain Long
-> long
-> Long
.
Long.valueOf
接受一个long
值,但您传递一个Long
值——强制拆箱。然而,紧随其后的是Long.valueOf
重新装箱该值并且表达式的计算结果Long
再次为 a 。FindBugs 检测到不必要的转换链Long
-> long
-> Long
。