不建议使用构造函数Integer(int),Double(double),Long(long)等
问题内容:
在工作时,我得到了警告
The constructor Integer(int) is deprecated
而且我找不到在线替代构造函数/解决方案。我该如何解决这个问题?
更新
对于其他原始包装器类型的构造函数,我将收到类似的警告;例如
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
?
问题答案:
您可以使用
Integer integer = Integer.valueOf(i);
不推荐使用。很少适合使用此构造函数。通常,静态工厂valueOf(int)是更好的选择,因为它可能会产生明显更好的空间和时间性能。构造一个新分配的Integer对象,该对象表示指定的int值。
主要区别在于,valueOf
由于Integer
缓存了小型实例,因此您将不会总是获得新实例。
所有原始包装类型的(Boolean
,Byte
,Char
,Short
,Integer
,Long
,Float
和Double
)都采用了相同的模式。通常,替换为:
new <WrapperType>(<primitiveType>)
与
<WrapperType>.valueOf(<primitiveType>)
(请注意,上面提到的缓存行为随类型和Java平台而有所不同,但是尽管存在这些差异,Java 9+弃用仍然适用。)