构造函数 Integer(int)、Double(double)、Long(long) 等已弃用

2022-08-31 13:23:00

工作时,我收到了警告

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


答案 1

您可以使用

Integer integer = Integer.valueOf(i);

构造函数的 javadoc

荒废的。很少适合使用此构造函数。静态工厂值Of(int)通常是更好的选择,因为它可能会产生明显更好的空间和时间性能。构造一个新分配的 Integer 对象,该对象表示指定的 int 值。

主要区别在于,由于缓存了小实例,您不会总是获得新实例。valueOfInteger


所有原始包装类型(、 、 、 、 、 和 ) 都采用了相同的模式。通常,将:BooleanByteCharShortIntegerLongFloatDouble

    new <WrapperType>(<primitiveType>)

    <WrapperType>.valueOf(<primitiveType>)

(请注意,上面提到的缓存行为因类型和 Java 平台而异,但尽管存在这些差异,仍适用 Java 9+ 弃用。


答案 2

推荐