不建议使用构造函数Integer(int),Double(double),Long(long)等 [英] The constructors Integer(int), Double(double), Long(long) and so on are deprecated
问题描述
在工作时,我得到了警告
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 ?
更新
对于其他原始包装类型,我将得到类似的警告.例如
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
对这些类是否适用与 Integer
相同的解决方案?
Does the same solution apply to these classes as for Integer
?
推荐答案
您可以使用
Integer integer = Integer.valueOf(i);
来自构造函数:
已弃用.很少适合使用此构造函数.这静态工厂valueOf(int)通常是一个更好的选择,因为它是可能会产生明显更好的时空性能.构造一个新分配的Integer对象,该对象表示指定的int值.
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.
主要区别在于,由于小型 Integer
实例被缓存,因此您将不会总是获得带有 valueOf
的新实例.
The main difference is that you won't always get a new instance with valueOf
as small Integer
instances are cached.
所有原始包装器类型( Boolean
, Byte
, Char
, Short
, Integer
, Long
, Float
和 Double
)采用了相同的模式.通常,替换为:
All of the primitive wrapper types (Boolean
, Byte
, Char
, Short
, Integer
, Long
, Float
and Double
) have adopted the same pattern. In general, replace:
new <WrapperType>(<primitiveType>)
与
<WrapperType>.valueOf(<primitiveType>)
(请注意,上述缓存行为随类型和Java平台而有所不同,但是尽管存在这些差异,但仍适用Java 9 +.)
(Note that the caching behavior mentioned above differs with the type and the Java platform, but the Java 9+ deprecation applies notwithstanding these differences.)
这篇关于不建议使用构造函数Integer(int),Double(double),Long(long)等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!