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是在堆中创建了不同的对象。
阅读全文
0 0
- Integer应用了享元模式
- 享元设计模式与Integer类
- Integer注意_享元设计模式
- Integer.valueof()学习之享元模式
- Integer的享元模式解析
- 从Integer来看享元设计模式
- Java中int与Integer的区别及享元模式在常量池中的应用
- Integer类自动装箱、拆箱与享元模式
- 基本类型Integer的享元设计模式
- Android设计模式应用-享元模式
- 设计模式的应用场景(12)--享元模式
- 享元模式在poi excel表格生成中的应用
- Java之自动拆装箱及享元模式应用
- 享元模式在Android中的简单应用
- 深入浅出享元模式
- 享元模式
- 享元(FlyWeight)模式
- 享元模式
- java 集合类结构图
- Python高级
- sqlserver查询数据库所有存储过程、触发器、索引信息
- ora-01033错误恢复
- js控制 radio 选中状态
- Integer应用了享元模式
- 即时通讯
- tensorflow安装
- mac OSx 打包成dmg文件
- homestead安装php redis扩展 教程
- 几款开发 CSS 最好的前端开发工具
- UVALive-7509-Dome and Steles
- QFileInfo的各种文件名的区别
- 洛谷11月月赛 T3 斐波那契数列