Integer应用了享元模式

来源:互联网 发布:淘宝男士服装店铺推荐 编辑:程序博客网 时间:2024/05/16 07:18

当这个方法运行时会输出怎样的结果呢?

public class Test {        public static void main(String[] args) {          Integer i1 = 127;          Integer i2 = 127;          System.err.println(i1 == i2);                    i1 = 128;          i2 = 128;          System.err.println(i1 == i2);      }  }  

这个运行的结果是,第一个为true,第二个为false。为什么会这样呢?Integer到底有怎样的密码呢?

Integer.java中的缓存整数的类IntegerCache类。当整数在【-128,127】范围内,自动装箱时不会创建新的对象,是共享的。这是享元模式的一种应用。

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

由于这个原因,所以,当Integer的数值在-128到127之间时,创建的对象只要值是相同的,那么这两个对象就是同一个对象,可以用==进行比较。

再来看一下这种情况,结果怎样呢?

public class Test{      public static void main(String[] args) {    Integer i1 = new Integer(97);        Integer i2 = new Integer(97);        System.out.println(i1 == i2);    }}
这时便是false了,new是在堆中创建了不同的对象。



原创粉丝点击