在JDK5之后,引入了自动装箱与拆箱(Autoboxing and unboxing)
创建一个Integer对象时,却可以这样:
Integer i = 100;但是和 int i = 100; 不一样的
实际上,执行上面那句代码的时候,系统为我们执行了:Integer i = Integer.valueOf(100); 即基本数据类型的自动装箱功能。
自动拆箱(unboxing),也就是将对象中的基本数据从对象中自动取出。如下可实现自动拆箱:
1 Integer i = 0; //自动装箱
2 int t = i; //自动拆箱,实际上执行了 int t = i.intValue();完成拆箱
-
基本数据类型与对象的差别 (网络摘取)
基本数据类型不是对象,也就是使用int、double、boolean等定义的变量、常量。
基本数据类型没有可调用的方法。
eg: int t = 1; t. 后面是没有方法滴。
Integer t =1; t. 后面就有很多方法可让你调用了。
-
Integer的自动装箱
//在-128~127 之外的数
Integer i1 =200;
Integer i2 =200;
System.out.println("i1==i2: "+(i1==i2));
// 在-128~127 之内的数
Integer i3 =100;
Integer i4 =100;
System.out.println("i3==i4: "+(i3==i4));
输出的结果是:
i1==i2: false
i3==i4: true
说明:
equals() 比较的是两个对象的值(内容)是否相同。
"==" 比较的是两个对象的引用(内存地址)是否相同,也用来比较两个基本数据类型的变量值是否相等。
前面说过,int 的自动装箱,是系统执行了 Integer.valueOf(int i),先看看Integer.java的源码:
1
2
3
4
5
6
|
public
static
Integer valueOf(
int
i) {
if
(i >= -
128
&& i <= IntegerCache.high)
// 没有设置的话,IngegerCache.high 默认是127
return
IntegerCache.cache[i +
128
];
else
return
new
Integer(i);
}
|
对于–128到127(默认是127)之间的值,Integer.valueOf(int i) 返回的是缓存的Integer对象(并不是新建对象)
所以范例中,i3 与 i4实际上是指向同一个对象。
而其他值,执行Integer.valueOf(int i) 返回的是一个新建的 Integer对象,所以范例中,i1与i2 指向的是不同的对象。
当然,当不使用自动装箱功能的时候,情况与普通类对象一样,请看下例:
2 Integer i4 = new Integer( 100 );
3 System.out.println( " i3==i4: " + (i3 == i4)); // 显示false
-
String 的拆箱装箱
先看个例子:
2 String str2 = " abc " ;
3 System.out.println(str2 == str1); // 输出为 true
4 System.out.println(str2.equals(str1)); // 输出为 true
5
6 String str3 = new String( " abc " );
7 String str4 = new String( " abc " );
8 System.out.println(str3 == str4); // 输出为 false
9 System.out.println(str3.equals(str4)); // 输出为 true
这个怎么解释呢?貌似看不出什么。那再看个例子。
2 String e = " 23 " ;
3 e = e.substring( 0 , 1 );
4 System.out.println(e.equals(d)); // 输出为 true
5 System.out.println(e == d); // 输出为 false
参考:http://www.cnblogs.com/danne823/archive/2011/04/22/2025332.html