something interesting:

语法糖(Syntactic sugar),也译为糖衣语法,是由英国计算机科学家彼得·约翰·兰达(Peter J. Landin)发明的一个术语,指计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用。通常来说使用语法糖能够增加程序的可读性,从而减少程序代码出错的机会

先用 == 和 equals 比较一下

  1. package integer_int;
  2. /**
  3. * @ClassName Main
  4. * @Description TODO
  5. * @Author hasee
  6. * @Date 2019/12/14 19:07
  7. * @Version 1.0
  8. **/
  9. public class Main {
  10. /**
  11. * 主函数
  12. * @param args
  13. */
  14. public static void main(String[] args){
  15. Integer i = 10;
  16. Integer j = 10;
  17. //true
  18. System.out.println("use == "+(i == j));
  19. //true
  20. System.out.println("user equals "+i.equals(j));
  21. //上述相等是因为 -128<int<127
  22. //第一次声明会将 i 的值放入缓存中,第二次直接取缓存里面的数据,而不是重新创建一个Ingeter 对象
  23. //那么第一个打印结果因为 i = 10 在缓存表示范围内,所以为 true。
  24. Integer m = 128;
  25. Integer n = 128;
  26. System.out.println();
  27. //false
  28. System.out.println("use == "+(m == n));
  29. //true
  30. System.out.println("user equals "+m.equals(n));
  31. //上述第一个不相等是因为超出了 -128<int<127 的范围 用 == 得不到相等的true结构
  32. //上述第二个能相等是因为使用了equals
  33. int k = 10;
  34. System.out.println();
  35. //true
  36. System.out.println("use == "+(i == k));
  37. //true
  38. System.out.println("user equals "+i.equals(k));
  39. int kk = 128;
  40. System.out.println();
  41. //true
  42. System.out.println("use == "+(m == kk));
  43. //true
  44. System.out.println("user equals "+m.equals(kk));
  45. //上述不论 == 和 equals 都相等的原因是因为Integer自动拆箱
  46. Integer o = new Integer(10);
  47. Integer p = new Integer(10);
  48. System.out.println();
  49. //false
  50. System.out.println("use == "+(o == p));
  51. //new产生了两个新对象,不存在缓存,又且是 == 所以不相等
  52. //true
  53. System.out.println("use == "+(o.equals(p)));
  54. }
  55. }

Integer 类和 int 的区别

  ①、Integer 是 int 包装类,int 是八大基本数据类型之一(byte,char,short,int,long,float,double,boolean)
  ②、Integer 是类,默认值为null,int是基本数据类型,默认值为0;
  ③、Integer 表示的是对象,用一个引用指向这个对象,而int是基本数据类型,直接存储数值。

Integer 的自动拆箱和装箱

自动装箱:

  1. //Integer是包装类,使用应该是先实例对象Object obj = new Object();
  2. //Integer的自动装箱like this
  3. Integer i = 128;//无需声明
  4. //因为语法糖的存在,它的执行是在编译期,会根据代码的语法,
  5. //在生成class文件的时候,决定是否进行拆箱和装箱动作。
  6. //为什么可以这样,通过反编译工具,我们可以看到,生成的class文件是:
  7. Integer a = Integer.valueOf(128);
  8. //这就是基本数据类型的自动装箱,128是基本数据类型,然后被解析成Integer类。
  9. //注意:自动装箱规范要求
  10. byte<= 127char<=127、-128<=short <=127、-128<=int <=127都被包装到固定的对象中(缓存)。

自动拆箱:

  1. //我们将 Integer 类表示的数据赋值给基本数据类型int,就执行了自动拆箱。
  2. Integer a = new Integer(128);
  3. int m = a;
  4. //反编译生成的class文件:
  5. Integer a = new Integer(128);
  6. int m = a.intValue();

结论:

简单来讲:自动装箱就是Integer.valueOf(int i);自动拆箱就是 i.intValue();
换句话说:自动装箱就是“返回一个指定int值的Integer实例”;自动拆箱就是“以int类型返回该Integer的值”