代码之家  ›  专栏  ›  技术社区  ›  LB40

新整数与值

  •  67
  • LB40  · 技术社区  · 14 年前

    我在用 Sonar 为了使我的代码更清晰,它指出我正在使用 new Integer(1) 而不是 Integer.valueOf(1) . 因为看起来 valueOf 不会实例化新对象,因此内存更友好。怎样才能 价值 没有实例化一个新对象?它是如何工作的?所有整数都是这样吗?

    4 回复  |  直到 8 年前
        1
  •  69
  •   Adam Rosenfield    12 年前

    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

        2
  •  26
  •   Peter Mortensen icecrime    14 年前

    JavaDoc :

    公共静态整数值(int i) 返回表示指定int值的整数实例。如果不需要新的整数实例,则通常应优先使用此方法,而不是构造函数整数(int),因为通过缓存频繁请求的值,此方法可能会显著提高空间和时间性能。

    ValueOf 通常用于自动氧化,因此(用于自动氧化时)缓存的值至少为-128到127,以符合自动氧化规范。

    这里是 valueOf Sun 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);
    }
    
        3
  •  2
  •   ante.sabo    13 年前

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

    这样,如果你是一个没有经验的Java程序员,你可能会给自己带来很多问题,因为你会得出这样的结论。 Integer.valueOf(342)==Integer.valueOf(342) ,因为您可能(或不可能)对两个整数有相同的指针,并且您可能会以某种方式练习它,例如,您在C中学习的,这样会不时地向您显示错误,并且您将不知道这些错误来自何处…

        4
  •  2
  •   beresfordt user1762507    9 年前

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

    /**
     * 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() {}
    }
    

    从java. lang.Short,java. Lang.Byg和java. Lang.Lon创建一个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));
        }
    }