gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:44:13 25 4
gpt4 key购买 nike

在工作时,我收到了警告

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);

来自 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 的新实例,因为缓存了较小的 Integer 实例。


所有原始包装器类型(BooleanByteCharShortInteger LongFloatDouble) 都采用了相同的模式。一般来说,替换:

    new <WrapperType>(<primitiveType>)

    <WrapperType>.valueOf(<primitiveType>)

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

关于java - 构造函数 Integer(int)、Double(double)、Long(long) 等已弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47095474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com