Java 新整数与 valueOf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2974561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:06:59  来源:igfitidea点击:

New Integer vs valueOf

javasonarqube

提问by LB40

I was using Sonarto make my code cleaner, and it pointed out that I'm using new Integer(1)instead of Integer.valueOf(1). Because it seems that valueOfdoes not instantiate a new object so is more memory-friendly. How can valueOfnot instantiate a new object? How does it work? Is this true for all integers?

我正在使用声纳使我的代码更清晰,它指出我正在使用new Integer(1)而不是Integer.valueOf(1). 因为它似乎valueOf不会实例化一个新对象,所以对内存更友好。怎么valueOf不能实例化一个新对象?它是如何工作的?这对所有整数都是正确的吗?

采纳答案by Brett Kail

Integer.valueOf implements a cache for the values -128 to +127. See the last paragraph of the Java Language Specification, section 5.1.7, which explains the requirements for boxing (usually implemented in terms of the .valueOf methods).

Integer.valueOf 实现了值 -128 到 +127 的缓存。请参阅 Java 语言规范的最后一段,第 5.1.7 节,其中解释了装箱的要求(通常根据 .valueOf 方法实现)。

http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7

http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7

回答by pgras

From the JavaDoc:

JavaDoc

public static Integer valueOf(int i) Returns a Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values.

public static Integer valueOf(int i) 返回表示指定 int 值的 Integer 实例。如果不需要新的 Integer 实例,则通常应优先使用此方法而不是构造函数 Integer(int),因为此方法通过缓存频繁请求的值可能会产生明显更好的空间和时间性能。

ValueOfis generaly used for autoboxing and therefore (when used for autoboxing) caches at least values from -128 to 127 to follow the autoboxing specification.

ValueOf通常用于自动装箱,因此(当用于自动装箱时)缓存至少从 -128 到 127 的值以遵循自动装箱规范。

Here is the valueOfimplementation for Sun JVM 1.5.? Have a look at the whole class to see how the cache is initialized.

这是valueOfSun JVM 1.5的实现。?查看整个类以了解缓存是如何初始化的。

public static Integer valueOf(int i) {
    final int offset = 128;
    if (i >= -128 && i <= 127) { // must cache 
        return IntegerCache.cache[i + offset];
    }
    return new Integer(i);
}

回答by ante.sabo

they are pushing you to use valueOf()instead of new Integer()so the method valueOf()does it for you, and caches the value in case you want to get the same number again in future. In that case, method won't instatiate new Integer, but will give you the cached one, what will make 'creation' of new Integer a lot quicker and memory friendly process..

他们正在推动您使用valueOf()而不是new Integer()因此该方法valueOf()为您执行此操作,并缓存该值,以防您将来再次获得相同的数字。在这种情况下,方法不会实例化新的整数,但会给你缓存的,什么会使新整数的“创建”更快,内存友好的过程..

This way you may cause yourself alot of problems if you are unexperienced java programmer since you will conclude that Integer.valueOf(342)==Integer.valueOf(342), because you may (or may not) have the same pointer for two Integers, and probably you will practise it in a way, let's say, you learned in C#, so that will show you bugs from time to time, and you won't know how & where those came from...

这样,如果您是没有经验的 Java 程序员,您可能会给自己带来很多问题,因为您会得出这样的结论 Integer.valueOf(342)==Integer.valueOf(342),因为您可能(或可能没有)对两个整数使用相同的指针,并且可能您会以某种方式练习它,让我们说,你在 C# 中学习过,所以它会不时地向你展示错误,而你将不知道这些错误是如何以及从哪里来的......

回答by Dungeon Hunter

From the java.lang.Integer Source Code. Integer cache is configurable. To configure the Integer cache size other than Sun we need to use the System property java.lang.Integer.IntegerCache.highas per the source code.

来自 java.lang.Integer 源代码。整数缓存是可配置的。要配置 Sun 以外的 Integer 缓存大小,我们需要java.lang.Integer.IntegerCache.high根据源代码使用 System 属性。

/**
 * Cache to support the object identity semantics of autoboxing for values between 
 * -128 and 127 (inclusive) as required by JLS.
 *
 * The cache is initialized on first usage. During VM initialization the
 * getAndRemoveCacheProperties method may be used to get and remove any system
 * properites that configure the cache size. At this time, the size of the
 * cache may be controlled by the vm option -XX:AutoBoxCacheMax=<size>.
 */

// value of java.lang.Integer.IntegerCache.high property (obtained during VM init)
private static String integerCacheHighPropValue;

static void getAndRemoveCacheProperties() {
    if (!sun.misc.VM.isBooted()) {
        Properties props = System.getProperties();
        integerCacheHighPropValue =
            (String)props.remove("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null)
            System.setProperties(props);  // remove from system props
    }
}

private static class IntegerCache {
    static final int high;
    static final Integer cache[];

    static {
        final int low = -128;

        // high value may be configured by property
        int h = 127;
        if (integerCacheHighPropValue != null) {
            // Use Long.decode here to avoid invoking methods that
            // require Integer's autoboxing cache to be initialized
            int i = Long.decode(integerCacheHighPropValue).intValue();
            i = Math.max(i, 127);
            // Maximum array size is Integer.MAX_VALUE
            h = Math.min(i, Integer.MAX_VALUE - -low);
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);
    }

    private IntegerCache() {}
}

From java.lang.Short,java.lang.Byte and java.lang.Long creates a cache of 127 to -128

从 java.lang.Short,java.lang.Byte 和 java.lang.Long 创建一个 127 到 -128 的缓存

private static class LongCache {
    private LongCache() {
    }

    static final Long cache[] = new Long[-(-128) + 127 + 1];

    static {
        for (int i = 0; i < cache.length; i++)
            cache[i] = new Long(i - 128);
    }
}

private static class ShortCache {
    private ShortCache() {
    }

    static final Short cache[] = new Short[-(-128) + 127 + 1];

    static {
        for (int i = 0; i < cache.length; i++)
            cache[i] = new Short((short) (i - 128));
    }
}

private static class ByteCache {
    private ByteCache() {
    }

    static final Byte cache[] = new Byte[-(-128) + 127 + 1];

    static {
        for (int i = 0; i < cache.length; i++)
            cache[i] = new Byte((byte) (i - 128));
    }
}