something interesting:
语法糖(Syntactic sugar),也译为糖衣语法,是由英国计算机科学家彼得·约翰·兰达(Peter J. Landin)发明的一个术语,指计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用。通常来说使用语法糖能够增加程序的可读性,从而减少程序代码出错的机会
先用 == 和 equals 比较一下
package integer_int;
/**
* @ClassName Main
* @Description TODO
* @Author hasee
* @Date 2019/12/14 19:07
* @Version 1.0
**/
public class Main {
/**
* 主函数
* @param args
*/
public static void main(String[] args){
Integer i = 10;
Integer j = 10;
//true
System.out.println("use == "+(i == j));
//true
System.out.println("user equals "+i.equals(j));
//上述相等是因为 -128<int<127
//第一次声明会将 i 的值放入缓存中,第二次直接取缓存里面的数据,而不是重新创建一个Ingeter 对象
//那么第一个打印结果因为 i = 10 在缓存表示范围内,所以为 true。
Integer m = 128;
Integer n = 128;
System.out.println();
//false
System.out.println("use == "+(m == n));
//true
System.out.println("user equals "+m.equals(n));
//上述第一个不相等是因为超出了 -128<int<127 的范围 用 == 得不到相等的true结构
//上述第二个能相等是因为使用了equals
int k = 10;
System.out.println();
//true
System.out.println("use == "+(i == k));
//true
System.out.println("user equals "+i.equals(k));
int kk = 128;
System.out.println();
//true
System.out.println("use == "+(m == kk));
//true
System.out.println("user equals "+m.equals(kk));
//上述不论 == 和 equals 都相等的原因是因为Integer自动拆箱
Integer o = new Integer(10);
Integer p = new Integer(10);
System.out.println();
//false
System.out.println("use == "+(o == p));
//new产生了两个新对象,不存在缓存,又且是 == 所以不相等
//true
System.out.println("use == "+(o.equals(p)));
}
}
Integer 类和 int 的区别
①、Integer 是 int 包装类,int 是八大基本数据类型之一(byte,char,short,int,long,float,double,boolean)
②、Integer 是类,默认值为null,int是基本数据类型,默认值为0;
③、Integer 表示的是对象,用一个引用指向这个对象,而int是基本数据类型,直接存储数值。
Integer 的自动拆箱和装箱
自动装箱:
//Integer是包装类,使用应该是先实例对象Object obj = new Object();
//Integer的自动装箱like this
Integer i = 128;//无需声明
//因为语法糖的存在,它的执行是在编译期,会根据代码的语法,
//在生成class文件的时候,决定是否进行拆箱和装箱动作。
//为什么可以这样,通过反编译工具,我们可以看到,生成的class文件是:
Integer a = Integer.valueOf(128);
//这就是基本数据类型的自动装箱,128是基本数据类型,然后被解析成Integer类。
//注意:自动装箱规范要求
byte<= 127、char<=127、-128<=short <=127、-128<=int <=127都被包装到固定的对象中(缓存)。
自动拆箱:
//我们将 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();
换句话说:自动装箱就是“返回一个指定int值的Integer实例”;自动拆箱就是“以int类型返回该Integer的值”