一个关于Integer的秘密
2016-02-17 12:16
246 查看
先让大家看一段简单的代码:
大家猜一下。输出的结果会是什么?我想大多数刚開始学习的人都会觉得是:true true。但是,实际呢?正确答案是:true
false。这时,是不是有人開始纳闷了。不禁问道:为什么呢?逻辑都一样。仅仅是数字不同,难道跟数字有关?恭喜你,答对了,确实跟数字有关。
以下我就带大家看看当中的缘由。
我们看一下integer源代码中的两个方法:
当我们初始化一个integer类型的变量时,如:Integer a = 1,实际上它调用了integer中的valueOf方法,相当于Integera
= Integer.valueOf(1),而在这种方法内部有一个缓存的机制。
它会推断你给变量赋的值是否在-128——127之间。假设是,那么它直接从缓存里去取对象。反之才会新创建一个对象。
也就是说。当程序运行Integerb = 1时。缓存中已经存在这个integer对象,它直接将b指向缓存中的对象,结果就是a、b指向同一对象,而c、d就不同了,它们两个终于会指向两个新创建的不同的对象,运行c==d时,自然不会相等。如今大家该明确了吧。
明确了这个原理,最重要的还是要应用于实际。当我们在程序中操作小整型数字的时候,我们要充分利用integer中的缓存机制,节省程序创建对象的时间,以此来提高我们程序的效率。
最后。假设有人关心==与equal的差别,请看以下这篇文章:
具体解释java中equals和==
的差别
public static voidmain(String[] args) { Integera = 1; Integerb = 1; Integerc = 222; Integerd = 222; System.out.println(a== b); System.out.println(c== d); }
大家猜一下。输出的结果会是什么?我想大多数刚開始学习的人都会觉得是:true true。但是,实际呢?正确答案是:true
false。这时,是不是有人開始纳闷了。不禁问道:为什么呢?逻辑都一样。仅仅是数字不同,难道跟数字有关?恭喜你,答对了,确实跟数字有关。
以下我就带大家看看当中的缘由。
我们看一下integer源代码中的两个方法:
publicstatic Integer valueOf(int i) { if(i >= -128 && i <=IntegerCache.high) return IntegerCache.cache[i + 128]; else return new Integer(i); } privatestatic class IntegerCache { static final int high; static final Integer cache[]; static { final int low = -128; // high value may be configured byproperty int h = 127; if (integerCacheHighPropValue !=null) { // Use Long.decode here toavoid invoking methods that // require Integer's autoboxingcache to be initialized int i =Long.decode(integerCacheHighPropValue).intValue(); i = Math.max(i, 127); // Maximum array size isInteger.MAX_VALUE h = Math.min(i,Integer.MAX_VALUE - -low); } high = h; cache = new Integer[(high - low) +1]; int j = low; for(int k = 0; k < cache.length;k++) cache[k] = new Integer(j++); } private IntegerCache() {} }
当我们初始化一个integer类型的变量时,如:Integer a = 1,实际上它调用了integer中的valueOf方法,相当于Integera
= Integer.valueOf(1),而在这种方法内部有一个缓存的机制。
它会推断你给变量赋的值是否在-128——127之间。假设是,那么它直接从缓存里去取对象。反之才会新创建一个对象。
也就是说。当程序运行Integerb = 1时。缓存中已经存在这个integer对象,它直接将b指向缓存中的对象,结果就是a、b指向同一对象,而c、d就不同了,它们两个终于会指向两个新创建的不同的对象,运行c==d时,自然不会相等。如今大家该明确了吧。
明确了这个原理,最重要的还是要应用于实际。当我们在程序中操作小整型数字的时候,我们要充分利用integer中的缓存机制,节省程序创建对象的时间,以此来提高我们程序的效率。
最后。假设有人关心==与equal的差别,请看以下这篇文章:
具体解释java中equals和==
的差别
相关文章推荐
- BZOJ 3307: 雨天的尾巴( LCA + 线段树合并 )
- R4ndom破解教程全文翻译(For新手):第二章
- ROS(机器人操作系统)学习(二)ROS文件系统
- CentOS 6.6 下源码编译安装MySQL 5.7.5
- CommonAdapter
- 排序——选择排序
- 指针常量~常量指针
- swift 中cell 自适应label高度
- SQL Server无法连接到DESKTOP-QIIG 55L:无法打开SQL Server连接 详解
- c#大圣之路笔记——绑定dropdown数据的基本方法
- BZOJ 1164 Baltic2008 Game
- Unicode 字符集学习笔记
- 博客园 Mac客户端 2.0 正式发布!
- Android命名规则
- PHP-Apache命令提示符权限设置
- XCode6 设置Icon
- android:listview实现qq,微信好友列表(头像,昵称,个性签名)
- 利用栈做的中缀计算器雏形
- 如何自定义android chooser 应用选择器
- 将Cocos项目部署到Android Studio工程中