Integer类和int类在Java 中有什么不同

Integer类和int类在Java 中有什么不同?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

代码实例如下

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); }

  打印结果为:

  

Integer类和int类在Java 中有什么不同

  首先,直接声明Integer i = 10,会自动装箱变为Integer i = Integer.valueOf(10);Integer i 会自动拆箱为 i.intValue()。

  ①、第一个打印结果为 true

  对于 i == j ,我们知道这是两个Integer类,他们比较应该是用equals,这里用==比较的是地址,那么结果肯定为false,但是实际上结果为true,这是为什么?

  我们进入到Integer 类的valueOf()方法:

  

Integer类和int类在Java 中有什么不同

  分析源码我们可以知道在 i >= -128 并且 i <= 127 的时候,第一次声明会将 i 的值放入缓存中,第二次直接取缓存里面的数据,而不是重新创建一个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。

5、测试

Integer a = 1;
Integer b = 2;
Integer c = 3;
Integer d = 3;

Integer e = 321;
Integer f = 321;

Long g = 3L;
Long h = 2L;

System.out.println(c == d);
System.out.println(e == f);
System.out.println(c == (a + b));
System.out.println(c.equals((a+b)));
System.out.println(g == (a+b));
System.out.println(g.equals(a+b));
System.out.println(g.equals(a+h));

  反编译结果:

  

Integer类和int类在Java 中有什么不同

  分析:第一个和第二个结果没什么疑问,Integer类在-128到127的缓存问题;

  第三个由于 a+b包含了算术运算,因此会触发自动拆箱过程(会调用intValue方法),==比较符又将左边的自动拆箱,因此它们比较的是数值是否相等。

  第四个对于c.equals(a+b)会先触发自动拆箱过程,再触发自动装箱过程,也就是说a+b,会先各自调用intValue方法,得到了加法运算后的数值之后,便调用Integer.valueOf方法,再进行equals比较。

  第五个对于 g == (a+b),首先计算 a+b,也是先调用各自的intValue方法,得到数值之后,由于前面的g是Long类型的,也会自动拆箱为long,==运算符能将隐含的将小范围的数据类型转换为大范围的数据类型,也就是int会被转换成long类型,两个long类型的数值进行比较。

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

相关文章阅读