进一步理解Integer
自动装箱与拆箱
Integer自动装箱即将基本数据类型封装成包装类型,生成Integer对象。
Integer拆箱即将Integer对象拆箱成基本数据类型。
Integer i = 12; //自动装箱,调用了Integer.valueOf(12)静态方法生成Integer对象
int a = i; //自动拆箱,调用intValue()方法,返回i对象中的value属型。
为什么是这些方法呢,让我们看下字节码。
//javap -c Main
public static void main(java.lang.String[]);
Code:
0: bipush 12
2: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
5: astore_1
6: aload_1
7: invokevirtual #3 // Method java/lang/Integer.intValue:()I
10: istore_2
11: return
由字节码可以看出,在12赋值给i时,是调用了Integer静态方法valueOf,传入12,再返回了一个Integer对象。在a=i时,则是调用了实例方法intValue,返回了i对象的value属性。
public int intValue() {
return value;
}
数据缓存
public static void main(String[] args) {
// Integer 高频区缓存范围 -128~127
Integer num1 = 127;
Integer num2 = 127;
// Integer 取值 127 == 结果为 true(值127 num1==num2 => true)
System.out.println("值127 num1==num2 => " + (num1 == num2));
Integer num3 = 128;
Integer num4