您好,欢迎访问一九零五行业门户网

深入理解java中的自动装箱与拆箱

一、什么是装箱,什么是拆箱
装箱:把基本数据类型转换为包装类。
拆箱:把包装类转换为基本数据类型。
基本数据类型所对应的包装类:
int(几个字节4)- integer
byte(1)- byte
short(2)- short
long(8)- long
float(4)- float
double(8)- double
char(2)- character
boolean(未定义)- boolean
免费在线视频学习教程推荐:java视频教程
二、先来看看手动装箱和手动拆箱
例子:拿int和integer举例
integer i1=integer.valueof(3);int i2=i1.intvalue();

手动装箱是通过valueof完成的,大家都知道 = 右边值赋给左边,3是一个int类型的,赋给左边就变成了integer包装类。
手动拆箱是通过intvalue()完成的,通过代码可以看到 i1 从integer变成了int
三、手动看完了,来看自动的
为了减轻技术人员的工作,java从jdk1.5之后变为了自动装箱与拆箱,还拿上面那个举例:
手动:
integer i1=integer.valueof(3);int i2=i1.intvalue();

自动
integer i1=3;int i2=i1;
这是已经默认自动装好和拆好了。
四、从几道题目中加深对自动装箱和拆箱的理解
(1)
integer a = 100;int b = 100;system.out.println(a==b);结果为 true
原因:a 会自动拆箱和 b 进行比较,所以为 true
(2)
integer a = 100;integer b = 100;system.out.println(a==b);//结果为trueinteger a = 200;integer b = 200;system.out.println(a==b);//结果为false
这就发生一个有意思的事了,为什么两个变量一样的,只有值不一样的一个是true,一个是false。
原因:这种情况就要说一下 == 这个比较符号了,== 比较的内存地址,也就是new 出来的对象的内存地址,看到这你们可能会问这好像没有new啊,但其实integer a=200; 200前面是默认有 new integer的,所用内存地址不一样 == 比较的就是 false了,但100为什么是true呢?这是因为 java中的常量池 我们可以点开 integer的源码看看。
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; }
在对 -128到127 之间的进行比较时,不会new 对象,而是直接到常量池中获取,所以100是true,200超过了这个范围然后进行了 new 的操作,所以内存地址是不同的。
(3)
integer a = new integer(100);integer b = 100;system.out.println(a==b);//结果为false
这跟上面那个100的差不多啊,从常量池中拿,为什么是false呢?
原因:new integer(100)的原因,100虽然可以在常量池中拿,但架不住你直接给new 了一个对象啊,所用这俩内存地址是不同的。
(4)
integer a = 100;integer b= 100;system.out.println(a == b);//结果truea = 200;b = 200;system.out.println(c == d);//结果为false
原因:= 号 右边值赋给左边a,b已经是包装类了,200不在常量池中,把int 类型200 赋给包装类,自动装箱又因为不在常量池中所以默认 new了对象,所以结果为false。
更多相关文章教程可以访问:java语言入门
以上就是深入理解java中的自动装箱与拆箱的详细内容。
其它类似信息

推荐信息