Java 不推荐使用构造函数 Integer(int)、Double(double)、Long(long) 等
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47095474/
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
The constructors Integer(int), Double(double), Long(long) and so on are deprecated
提问by DeSpeaker
While working, I got the warning
在工作时,我收到警告
The constructor Integer(int) is deprecated
and I couldn't find an alternative constructor/solution online. How can I resolve this issue ?
我在网上找不到替代的构造函数/解决方案。我该如何解决这个问题?
UPDATE
更新
I will get a similar warning with constructors for other primitive wrapper types; e.g.
对于其他原始包装器类型的构造函数,我将收到类似的警告;例如
The constructor Boolean(boolean) is deprecated
The constructor Byte(byte) is deprecated
The constructor Short(short) is deprecated
The constructor Character(char) is deprecated
The constructor Long(long) is deprecated
The constructor Float(float) is deprecated
The constructor Double(double) is deprecated
Does the same solution apply to these classes as for Integer
?
相同的解决方案是否适用于这些类Integer
?
采纳答案by Denys Séguret
You can use
您可以使用
Integer integer = Integer.valueOf(i);
From the javadoc of the constructor:
Deprecated. It is rarely appropriate to use this constructor. The static factory valueOf(int) is generally a better choice, as it is likely to yield significantly better space and time performance. Constructs a newly allocated Integer object that represents the specified int value.
已弃用。很少适合使用此构造函数。静态工厂 valueOf(int) 通常是更好的选择,因为它可能会产生明显更好的空间和时间性能。构造一个新分配的 Integer 对象,表示指定的 int 值。
The main difference is that you won't always get a new instance with valueOf
as small Integer
instances are cached.
主要区别在于,valueOf
由于Integer
缓存了小实例,因此您不会总是获得新实例。
All of the primitive wrapper types (Boolean
, Byte
, Char
, Short
, Integer
, Long
, Float
and Double
) have adopted the same pattern. In general, replace:
所有原始包装类型的(Boolean
,Byte
,Char
,Short
,Integer
,Long
,Float
和Double
)都采用了相同的模式。一般来说,替换:
new <WrapperType>(<primitiveType>)
with
和
<WrapperType>.valueOf(<primitiveType>)
(Note that the caching behavior mentioned above differs with the type and the Java platform, but the Java 9+ deprecation applies notwithstanding these differences.)
(请注意,上面提到的缓存行为因类型和 Java 平台而异,但尽管存在这些差异,但 Java 9+ 的弃用仍然适用。)