Integer中的享元模式
对象Integer也用到了享元模
public static void main(String[] args) { Integer a = Integer.valueOf(127); Integer b = 127; Integer c = Integer.valueOf(128); Integer d = 128; System.out.println(a == b); //true System.out.println(c == d); //false }
之所以得到这样的结果,是因为Integer用到了享元模式,来看Integer的源码。
由上可知,Integer源码中的valueOf()方法做了一个条件判断,如果目标值在-128~127,则直接从缓存中取值,否则新建对象。JDK为何要这样做呢?因为-128~127的数据在int范围内是使用最频繁的,为了减少频繁创建对象带来的内存消耗,这里就用到了享元模式,以提高性能。
Long中的享元模式
和Integer类似,Long源码也用到了享元模式,将-128~127的值缓存起来,源码如下。