关于Java包装类装箱拆箱的小例子(二)

2014-11-24 01:40:06 · 作者: · 浏览: 1
System.out.println(" autov3 == autov4 is "+ (autov3 == autov4));
System.out.println(" vv3 == vv4 is "+ (vv3 == vv4));

System.out.println("-----------------------------------------------------");

String strv3 = "200";
String strv4 = "200";
String stringv3 = new String("200");
String stringv4 = new String("200");
Integer strvalue3 = Integer.parseInt(strv3);
Integer strvalue4 = Integer.parseInt(strv4);
Integer stringvalue3 = Integer.parseInt(stringv3);
Integer stringvalue4 = Integer.parseInt(stringv4);
Integer newstrv3 = new Integer(strv3);
Integer newstrv4 = new Integer(strv4);

System.out.println(" strv3 == strv4 is "+ (strv3 == strv4));
System.out.println(" stringv3 == stringv4 is "+ (stringv3 == stringv4));
System.out.println(" stringv3 equals stringv4 is "+ (stringv3.equals(stringv4)));
System.out.println(" strvalue3 == strvalue4 is "+ (strvalue3 == strvalue4));
System.out.println(" stringvalue3 == stringvalue4 is "+ (stringvalue3 == stringvalue4));
System.out.println(" newstrv3 == newstrv4 is "+ (newstrv3 == newstrv4));
System.out.println(" newstrv3 equals newstrv4 is "+ (newstrv3.equals(newstrv4)));

System.out.println("-----------------------------------------------------");

}
}

运行结果:
Java代码
v1 == v2 is true
autovalue1 == autovalue2 is true
value1 == value2 is true
va1 == va2 is false
va1 equals va2 is true
autov1 == autov2 is true
vv1 == vv2 is true
----------------------------------------------------
strv1 == strv2 is true
stringv1 == stringv2 is false
stringv1 equals stringv2 is true
strvalue1 == strvalue2 is true
stringvalue1 == stringvalue2 is true
newstrv1 == newstrv2 is false
newstrv1 equals newstrv2 is true
----------------------------------------------------
v3 == v4 is true
autovalue3 == autovalue4 is false
value3 == value4 is false
va3 == va4 is false
va3 equals va4 is true
autov3 == autov4 is true
vv3 == vv4 is true
----------------------------------------------------
strv3 == strv4 is true
stringv3 == stringv4 is false
stringv3 equals stringv4 is true
strvalue3 == strvalue4 is false
stringvalue3 == stringvalue4 is false
newstrv3 == newstrv4 is false
newstrv3 equals newstrv4 is true
----------------------------------------------------

小结:
对于new创建出的两个对象,用==比较肯定是不同的,因为指向的不是同一内存
Integer装箱过程中调用的是valueOf方法,而 valueOf方法对值在-128到127之间的数值缓存了,源代码如下:

Java代码
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}

可见,Integer缓存中有一个静态的Integer数组,在类加载时就将-128 到 127 的Integer对象创建了,并保存在cache数组中,一旦程序调用valueOf 方法,如果i的值是在-128 到 127 之间就直接在cache缓存数组中去取Integer对象。