享元模式
享元模式:会将[-128,127]范围内的整数放入一个缓存池中,如果超过了这个范围内会在堆中创建对象
注意:
- 凡是new出来的都会在堆中创建对象
- 浮点数没有享元模式
代码示例:
public class Demo {
public static void main(String[] args) {
Integer i1 = 12;
Integer i2 = 12;
System.out.println(i1 == i2);//true
Integer i3 = 200;
Integer i4 = 200;
System.out.println(i3 == i4);//false
Integer i5 = new Integer(12);
Integer i6 = new Integer(12);
System.out.println(i5 == i6);//true
}
}
运行结果
true
false
false
堆栈分析:i1和i2持有相同的地址,i3和i4持有不同地址