封装数据类型中的对象缓存

深入理解 Integer

简介

Integer 是基本数据类型 int 的封装类型,使用位移的方式实现大部分操作。
提供了 int 转 String,String 转 int,以及处理 int 时的一些常量和方法。

对象缓存

先看代码

        int a = 127;
        int b = 128;
        int c = -128;
        int d = -129;

        Integer e = 127;
        Integer f = 127;
        Integer g = new Integer(127);

        Integer h = 128;
        Integer i = 128;
        Integer j = new Integer(128);

        Integer k = -128;
        Integer l = -128;
        Integer m = new Integer(-128);

        Integer n = -129;
        Integer o = -129;
        Integer p = new Integer(-129);

        System.out.println(a == e);            // true
        System.out.println(a == g);            // true
        System.out.println(e == f);            // true
        System.out.println(e == g);            // false
        System.out.println(e.equals(a));       // true
        System.out.println(g.equals(a));       // true
        System.out.println(e.equals(f));       // true
        System.out.println(e.equals(g));       // true

双等号 ==

  1. 用于比较基本数据类型的时候比较的是数值是否相等
  2. 用于比较两个对象时比较的是两个对象的内存地址

Integer 对象的两种创建方式
3. 直接赋值: 例如:Integer a = 1;
4. 构造函数: 例如:Integer a = new Integer(1);
直接赋值方式:通过 IntegerCache 对象缓存进行复制,缓存数值的范围为 [-128, 127],java.lang.Integer.IntegerCache.high 可以设置缓存的最大值,-XX:AutoBoxCacheMax=<size>
构造函数方式:通过 Integer 的构造函数创建的 Integer 对象,不会从缓存中赋值,而是创建一个新的对象。

缓存对象代码:

private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

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

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

拓展

  1. Byte、Short、Integer、Long 都具有对象缓存。
  2. 对象缓存是为了提高性能;
  3. 缓存以支持 JLS 要求的 -128(含) 到 127(含)之间的值的自动装箱的对象标识语义。

猜你喜欢

转载自blog.csdn.net/dejunyang/article/details/109196060