当前位置 博文首页 > moon_blade的博客:基础类型和包装类型
基础类型 | 包装类型 |
---|---|
byte | java.lang.Byte |
short | java.lang.Short |
int | java.lang.Integer |
long | java.lang.Long |
float | java.lang.Float |
double | java.lang.Double |
boolean | java.lang.Boolean |
char | java.lang.Character |
自动装箱是指java编译器将基础类型自动转换为对应的包装类型。
Integer a = 10;//Integer a = Integer.valueOf(10);
public static Integer show(Integer iParam){
System.out.println("autoboxing example - method invocation i: " + iParam);
return iParam;
}
show(3); //autoboxing
public static void main(String[] args) {
Integer a = 3;
}
对应的字节码为public static void main(java.lang.String[]);
Code:
0: iconst_3
1: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
4: astore_1
5: return
与自动装箱相对,自动编译器是指java编译器将包装类型自动转换为对应的基础类型。
Integer oldCount = new Integer(10);
int newCount = increment(oldCount);
private static int increment(int count) {
return ++count;
}
Integer a = new Integer(3);
int b = a;
Integer a = new Integer(3);
int b = a + 1;
public static void main(String[] args) {
Integer a = new Integer(3);
int b = a + 1;
}
对应的字节码为public static void main(java.lang.String[]);
Code:
0: new #2 // class java/lang/Integer
3: dup
4: iconst_3
5: invokespecial #3 // Method java/lang/Integer."<init>":(I)V
8: astore_1
9: aload_1
10: invokevirtual #4 // Method java/lang/Integer.intValue:()I
13: iconst_1
14: iadd
15: istore_2
16: return
为了减少自动装箱产生的无用中间对象对内存和垃圾回收的压力,Byte、Short、Integer、Long、Boolean、Character都带有缓存用来存储和复用常用的数据对象(float和double没有)。除了Integer、Boolean以外,其他包装类型的缓存策略均一样。
以上所有缓存只有使用包装类型的静态方法valueOf()生成对象时生效,包括主动调用、间接调用、自动装箱。
示例如下:
public class AutoboxingTest {
public static void main(String args[]) {
// Example 1: == comparison pure primitive – no autoboxing
int i1 = 1;
int i2 = 1;
System.out.println("i1==i2 : " + (i1 == i2)); // true
// Example 2: equality operator mixing object and primitive
Integer num1 = 1; // autoboxing
int num2 = 1;
System.out.println("num1 == num2 : " + (num1 == num2)); // true
// Example 3: special case - arises due to autoboxing in Java
Integer obj1 = 1; // autoboxing will call Integer.valueOf()
Integer obj2 = 1; // same call to Integer.valueOf() will return same
// cached Object
System.out.println("obj1 == obj2 : " + (obj1 == obj2)); // true
// Example 4: equality operator - pure object comparison
Integer one = new Integer(1); // no autoboxing
Integer anotherOne = new Integer(1);
System.out.println("one == anotherOne : " + (one == anotherOne)); // false
}
}
Output:
i1==i2 : true
num1 == num2 : true
obj1 == obj2 : true
one == anotherOne : false
cs