1 什么是拆箱和装箱?
装箱:用基本类型对象的引用类型包装基本类型,使其具有对象的性质,比喻把int包装成Integer,
拆箱:拆箱装箱是相反的操作,就是把类类型转化为基本类型,比喻把Integer转化为int
比喻:Integer i=2; //装箱,此时会自动调用valueOf方法,即和 Integer i=Integer.valueOf(2)等同
int j=i; //拆箱 ,此时把类类型转化为基本类型,此时调用了intValue方法
类似的拆箱还有i++;因为类类型不能直接参与加减乘除运算,必须转化为基本类型才可以
2 装箱和拆箱的针对对象:
基本类型:byte,int,short,long ,boolean,char,float,double
其中byte和int和short和long的拆箱装箱操作类似,float和double的拆箱和装箱操作类似
3 拆箱和装箱的具体实现办法:
装箱:对于类型x,调用valueOf()方法,比喻double类型,调用valueOf()
拆箱:对于类型x,调用xValue()方法,比喻double类型,调用doubleValue()方法
4 对int和double类型的剖析;
给出下列的输出结果:
<span style="font-size:18px;">Integer t1 = 100;
Integer t3 = 100;
System.out.println(t1==t3);</span>
输出结果:true
Integer s1 =200;
Integer s3 = 200;
System.out.println(s3==s1);
输出结果:false
分析:我们查看Integer的valueOf方法:
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
因为t1和t3都会进行装箱操作,调用valueOf方法,默认的high值为127,因此可以看出,当数值在-128到127之间时,返回的是cache数值中存放的对象,所以t1,t3指向同一个对象,但是对于大于127的数值,会重新new一个对象,故s1,s3指向的对象不同
注意:对于Integer i=new Integer(3),这样直接new一个对象的不涉及装箱操作
查看int类型的拆箱操作:
int t4=100;
Integer t3 = 100;
System.out.println(t3==t4);
结果:true
查看其intValue方法:
public int intValue() {
return value;
}
直接返回其数值,当基本类型进行比较大小的时候,直接比较数值大小,故而直接返回t3的数值和t4比较大小对于double类型:
Double double1=2.0;
Double double2=2.0;
System.out.println(double1==double2);
结果:false
这是double的valueOf方法:
public static Double valueOf(String s) throws NumberFormatException {
return new Double(FloatingDecimal.readJavaFormatString(s).doubleValue());
}
不难理解为什么是false了,这是因为double不能像int那样把一定范围内的数值存放在某个数组中,double可以表示无数个数字5 案例分析:
<pre name="code" class="java"> Integer t1 = 100;
Integer t2 = new Integer(100);
Integer t3 = 100;
int t4=100;
Integer s1 =200;
Integer s2 = new Integer(200);
Integer s3 = 200;
int s4 = 200;
String string1="abc";
String string2=new String("abc");
System.out.println(t1==t2);
System.out.println(t1==t3);
System.out.println(t3==t2);
System.out.println(t2==t4);
System.out.println(s1==s2);
System.out.println(s3==s1);
System.out.println(s3==s2);
System.out.println(s3==s4);
System.out.println(string1==string2);
输出结果:
false
true
false
true
false
false
false
true
false