一、什么是装箱,什么是拆箱
装箱:把基础数据范例转换为包装类。
拆箱:把包装类转换为基础数据范例。
基础数据范例所对应的包装类:
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);//效果为true Integer 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); //效果true a = 200; b = 200; System.out.println(c == d); //效果为false
缘由:= 号 右侧值赋给左侧a,b已是包装类了,200不在常量池中,把int 范例200 赋给包装类,自动装箱又由于不在常量池中所以默许 new了对象,所以效果为false。
更多相干文章教程能够接见:java言语入门
以上就是深切明白java中的自动装箱与拆箱的细致内容,更多请关注ki4网别的相干文章!