java Integer问题

时间:2018-11-19
本文章向大家介绍java Integer问题,需要的朋友可以参考一下

Integer是一个看着挺简单的,其实还是有点不一样,Integer是一个int的包装类,它是可以起到缓存作用的,在java基础里说过它的范围是(-128-127)在这个返回是有缓存的,不会创建新的Integer对象,并且可以设置它的最大值,通过设置VM参数。

下面先看一下源码:

 public static Integer valueOf(int i) {
        if(i >= -128 && i <= IntegerCache.high)
            return IntegerCache.cache[i + 128];
        else
            return new Integer(i);
    }
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() {}
    }
// 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
        }
    }

通过设置VM的java.lang.Integer.IntegerCache.high可以调整它的最大值。虽然它是在一个静态代码块里是一个常量,但是是在初始化的时候赋值的,所以没什么影响。

演示修改JVM参数(eclipse):

package test1;

public class Demo1 {
    
    public static void main(String[] args) {
        System.out.println(Integer.valueOf(200)==Integer.valueOf(200));
    }

}

输出结果:

false

怎么修改呢,看下面?

点击自己创建的项目,右键->Debug as ->Debug Configurations ->JavaApplication->点击自己的项目->Arguments->VM arguments设置->Apply->Debug

设置以后的结果: