The constructors Integer(int), Double(double), Long(long) and so on are deprecated

后端 未结 1 1584
栀梦
栀梦 2020-12-15 15:31

While working, I got the warning

The constructor Integer(int) is deprecated

and I couldn\'t find an alternative constructor/solution online

相关标签:
1条回答
  • 2020-12-15 16:01

    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.

    The main difference is that you won't always get a new instance with valueOf as small Integer instances are cached.


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

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

    0 讨论(0)
提交回复
热议问题