Integer 类和 int 基本数据类型的区别
引子
首先我们来看一段代码:
public static void main(String[] args) {
Integer i = 10;
Integer j = 10;
System.out.println(i == j);
Integer a = 128;
Integer b = 128;
System.out.println(a == b);
int k = 10;
System.out.println(k == i);
int kk = 128;
System.out.println(kk == a);
Integer m = new Integer(10);
Integer n = new Integer(10);
System.out.println(m == n);
}
看下输出结果:
true
false
true
true
false
Integer 类和 int 的区别
① Integer 是 int 包装类,int 是八大基本数据类型之一(byte,char,short,int,long,float,double,boolean)
② Integer 是类,默认值为null,int是基本数据类型,默认值为0;
③ Integer 表示的是对象,用一个引用指向这个对象,而int是基本数据类型,直接存储数值。
Integer 的自动拆箱和装箱
自动拆箱和自动装箱是 JDK1.5 以后才有的功能,也就是java当中众多的语法糖之一,它的执行是在编译期,会根据代码的语法,在生成class文件的时候,决定是否进行拆箱和装箱动作。
(1)自动装箱
一般我们创建一个类的时候是通过new关键字,比如:
Object obj = new Object();
但是对于 Integer 类,我们却可以这样:
Integer a = 128;
为什么可以这样,通过反编译工具,我们可以看到,生成的class文件是:
Integer a = Integer.valueOf(128);
这就是基本数据类型的自动装箱,128是基本数据类型,然后被解析成Integer类。
(2)自动拆箱
我们将 Integer 类表示的数据赋值给基本数据类型int,就执行了自动拆箱。
Integer a = new Integer(128);
int m = a;
反编译生成的class文件:
Integer a = new Integer(128);
int m = a.intValue();
简单来讲:自动装箱就是Integer.valueOf(int i);自动拆箱就是 i.intValue();
再来看开头的问题
public static void main(String[] args) {
Integer i = 10;
Integer j = 10;
System.out.println(i == j);
Integer a = 128;
Integer b = 128;
System.out.println(a == b);
int k = 10;
System.out.println(k == i);
int kk = 128;
System.out.println(kk == a);
Integer m = new Integer(10);
Integer n = new Integer(10);
System.out.println(m == n);
}
我们使用反编译工具Jad,得到的代码如下:
public static void main(String args[])
{
Integer i = Integer.valueOf(10);
Integer j = Integer.valueOf(10);
System.out.println(i == j);
Integer a = Integer.valueOf(128);
Integer b = Integer.valueOf(128);
System.out.println(a == b);
int k = 10;
System.out.println(k == i.intValue());
int kk = 128;
System.out.println(kk == a.intValue());
Integer m = new Integer(10);
Integer n = new Integer(10);
System.out.println(m == n);
}
输出结果:
true
false
true
true
false
首先,直接声明Integer i = 10,会自动装箱变为Integer i = Integer.valueOf(10);Integer i 会自动拆箱为 i.intValue()。
① 第一个打印结果为 true
对于 i == j ,我们知道这是两个Integer类,他们比较应该是用equals,这里用==比较的是地址,那么结果肯定为false,但是实际上结果为true,这是为什么?
我们进入到Integer 类的valueOf()方法:
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
分析源码我们可以知道在 i >= -128 并且 i <= 127 的时候,直接取缓存里面的数据,而不是重新创建一个Ingeter 对象。那么第一个打印结果因为 i = 10 在缓存表示范围内,所以为 true。
② 第二个打印结果为 false
从上面的分析我们知道,128是不在-128到127之间的,所以创建了一个新的Integer对象。故打印结果为false
③ 第三个打印结果为 true
Integer 的自动拆箱功能,也就是比较两个基本数据类型,结果当然为true
④ 第四个打印结果为 true
解释和第三个一样。int和integer(无论new否)比,都为true,因为会把Integer自动拆箱为int再去比较。
⑤ 第五个打印结果为 false
因为这个虽然值为10,但是我们都是通过 new 关键字来创建的两个对象,是不存在缓存的概念的。两个用new关键字创建的对象用 == 进行比较,结果当然为 false。