基本数据类型 | 包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
装箱/装包 : 把基本类型转变成包装类型 |
---|
拆箱/拆包:把一个包装类型转变成基本数据类型 |
---|
public class Test {
public static void main(String[] args) {
int a = 10;
Integer ii = a ; //自动装箱
Integer ii2 = new Integer(10);
int b = ii2;//自动拆箱
System.out.println(ii);
System.out.println(b);
}
}
通过访问上面代码的字节码文件,我们可以看到装箱的底层逻辑就是通过Integer这个类去调用valueOf
这个方法去装箱。
public class Test {
public static void main(String[] args) {
int a = 10;
// Integer ii = a ; //自动装箱
//根据字节码文件的内容可以将自动装箱的代码写成如下样式:
Integer ii = Integer.valueOf(a);//手动装箱
//================================================================================
Integer ii2 = new Integer(10);
// int b = ii2;//自动拆箱
int b = ii2.intValue();//手动拆箱
double d = ii2.doubleValue();//即使原来不是小数类型也能手动拆箱成小数类型
System.out.println(ii);
System.out.println(b);
System.out.println(d);
}
}
阿里巴巴面试题
public static void main(String[] args) {
Integer ii= 100;
Integer ii2 =100;
System.out.println(ii == ii2);
}
public static void main(String[] args) {
Integer ii= 200;
Integer ii2 =200;
System.out.println(ii == ii2);
}
valueOf
: public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
根据原代码我们可知道:cache是缓存数组,如果我们的i是在这个范围内的,他就会返回这个缓存数组,如果不在他就会再重新创建一个对象。如下图所示:
对于100,他是在我们数组的范围内,所以它无需创建对象,只需要在缓存数组中查找即可,这两个装箱的变量他们指向的都是同一个对象的地址所以返回true,而200则需要创建新的对象,这两个变量所指的不是同一个对象,内存地址也不一样,所以返回false。