一、初识
1、介绍
int 是Java八大基本数据类型之一,占据 4 个字节,范围是 -2^31~2^31 - 1,即 -2147483648~2147483647。而 Integer 是 int 包装类。
Integer 是类,默认值为null;int是基本数据类型,默认值为0。
Integer 表示的是对象,用一个引用指向这个对象,而 int 是基本数据类型,直接存储数值。
二、自动装箱和拆箱
1、案例
先看如下代码执行结果:
1 int i1 = 59; 2 3 Integer i2 = 59; 4 5 Integer i3 = new Integer(59); 6 Integer i4 = new Integer(59); 7 8 Integer i5 = Integer.valueOf(59); 9 Integer i6 = Integer.valueOf("59"); 10 11 System.out.println("----" + (i1 == i2)); // true 12 System.out.println("----" + (i1 == i3)); // true 13 System.out.println("----" + (i1 == i4)); // true 14 System.out.println("----" + (i1 == i5)); // true 15 System.out.println("----" + (i1 == i6)); // true 16 17 System.out.println("----" + (i2 == i3)); // false 18 System.out.println("----" + (i2 == i4)); // false 19 System.out.println("----" + (i2 == i5)); // true 20 System.out.println("----" + (i2 == i6)); // true 21 22 System.out.println("----" + (i3 == i4)); // false 23 System.out.println("----" + (i3 == i5)); // false 24 System.out.println("----" + (i3 == i6)); // false 25 26 System.out.println("----" + (i4 == i5)); // false 27 System.out.println("----" + (i4 == i6)); // false 28 29 System.out.println("----" + (i5 == i6)); // true
结论:先记下上述结果,后续会详细解释。
①基本数据类型 int 和其他任何形式创建的 Integer 比较都是true;
②Integer 表示的是对象,它是一个引用,存储的是对象在堆空间的地址。如图:
所以:int 的比较结果不难理解(后面还会解释),而对象的比较应该全是 false,因为他们创建了不同的对象,地址自然是不同的。那这里 i2 == i5,i2 == i6,i5 == i6 为什么是true呢?
因为 Integer 的自动拆箱和装箱原理,以及缓存机制。
自动拆箱和装箱是 JDK1.5 以后才有的功能,也是 Java 众多的语法糖之一,它的执行是在编译期,会根据代码的语法,在生成class文件的时候,决定是否进行拆箱和装箱动作。
2、自动拆箱
将 Integer 类表示的数据赋值给基本数据类型int,就执行了自动拆箱。
1 Integer a = new Integer(59); 2 int m = a;
反编译生成的class文件,上述表达式等价于:
1 Integer a = new Integer(59); 2 int m = a.intValue();
所以,在上述代码比较时,与 int 类型的比较都是true,因为包装类Integer会自动拆箱为数值型,数值的比较当然是true。等价于:
1 System.out.println("----" + (i1 == i2.intValue())); // true 2 System.out.println("----" + (i1 == i3.intValue())); // true 3 System.out.println("----" + (i1 == i4.intValue())); // true 4 System.out.println("----" + (i1 == i5.intValue())); // true 5 System.out.println("----" + (i1 == i6.intValue())); // true
3、自动装箱
一般地,创建对象是通过 new 关键字,比如:
1 Object obj = new Object();
对于 Integer 类,可以:
1 Integer a = 59;
反编译生成的class文件,上述表达式等价于:
1 Integer a = Integer.valueOf(59);
它其实等价的创建了一个对象,这种语法帮我们完成了而已。既然是对象,那么存储的就是引用,也就不难理解上述代码那些为 false 的结果。
那为什么 i2 == i5,i2 == i6,i5 == i6 是 true 呢?
4、缓存机制(新特性)
前面我们知道
1 Integer a = 59; 等价于 Integer a = Integer.valueOf(59);
查看一下valueOf()方法的源码,它有三个重载的方法。
源码示例:Integer.valueOf()
1 public static Integer valueOf(String s) throws NumberFormatException { 2 return Integer.valueOf(parseInt(s, 10)); 3 } 4 5 public static Integer valueOf(int i) { 6 if (i >= Integer.IntegerCache.low && i <= Integer.IntegerCache.high) 7 return Integer.IntegerCache.cache[i + (-Integer.IntegerCache.low)]; 8 return new Integer(i); 9 }