码迷,mamicode.com
首页 > 其他好文 > 详细

平时发现的一些有意思的小知识

时间:2018-12-26 16:55:05      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:project   amp   integer   类型   包装   eof   开始   对象   小知识   

平时遇到的一些自己开始不懂,后来看了下原理,豁然开朗的问题:

1.

 1 package day1226;
 2 
 3 /**
 4  * @author : hao
 5  * @project : StudySjms
 6  * @description :
 7  * @time : 2018/12/26 15:54
 8  */
 9 public class IntegerTest {
10 
11     public static void main(String[] args) {
12         Integer i1 = 100;
13         Integer i2 = 100;
14         Integer i3 = 200;
15         Integer i4 = 200;
16         System.out.println(i1==i2);    //true
17         System.out.println(i3==i4);  //false
18     }
19 }

这是为什么呢? 开始我以为只是false就好了

这里面体现了 原生类型和包装类型的装箱和拆箱。 

自动装箱的时候 实际上调用了Interger.valueOf(int)  ,拆箱的时候用的是initValue(Integer)

1     public static Integer valueOf(int i) {
2         if(i >= -128 && i <= IntegerCache.high)
3             return IntegerCache.cache[i + 128];
4         else
5             return new Integer(i);
6     }

可以发现如果值是-128-127范围内是返回缓存里的引用,如果不是新建一个对象,返回引用。所有上面200两个引用是两个对象的,所以false。

平时发现的一些有意思的小知识

标签:project   amp   integer   类型   包装   eof   开始   对象   小知识   

原文地址:https://www.cnblogs.com/haoerlv/p/10179685.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!