Java 处理警告的适当方法是什么:“x 类型的表达式被装箱到 x”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23317876/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:50:53  来源:igfitidea点击:

What is the appropriate way to handle warning: "The expression of type x is boxed into x"

javaeclipseautoboxing

提问by bn.

I'm notlooking to to turn off or ignore the warning as in The expression of type x is boxed into X?.

打算关闭或忽略警告,因为类型 x 的表达式被装箱到 X 中?.

I'd like to know what the correct way to handle/avoid this warning is if one was so inclined.

如果有人如此倾向,我想知道处理/避免此警告的正确方法是什么。

采纳答案by Jeffrey

Boxing and unboxing are operations you cando by hand, but they're build into the language to avoid the repetition you will undoubtedly encounter.

装箱和拆箱是您可以手动完成的操作,但它们已内置于语言中以避免您无疑会遇到的重复。

Integer obj = Integer.valueOf(5); // instead of Integer obj = 5;
int i = obj.intValue(); // instead of int i = obj;

In my opinion, the appropriate way to handle that warning to turn it off. But if that is not an option, you can do the above.

在我看来,处理该警告的适当方法是将其关闭。但是,如果这不是一种选择,您可以执行上述操作。

回答by user3577291

In my opinion its better to explicitly box-unbox the values as it makes the code more readable. Also there might be subtle differences when we use different approaches to boxing. For eg,

在我看来,最好显式地将值拆箱,因为它使代码更具可读性。当我们使用不同的拳击方法时,也可能会有细微的差异。例如,

Integer i = new Integer(1);

Integer j = Integer.valueOf(1);

According to javadoc Integer.valueOf()caches objects so i==jwill return false.

根据 javadocInteger.valueOf()缓存对象,因此i==j将返回false.

Also another way to explicitly box a primitive to Integer is

另一种将原语显式装箱为 Integer 的方法是

Integer k = (Integer)1;but this actually calls Integer.valueOf().

Integer k = (Integer)1;但这实际上称为Integer.valueOf().