语法糖-自动拆装箱的陷阱

		Integer a= 1;
		Integer b =2;
		Integer c= 3;
		Integer d = 3;
		Integer e = 321;
		Integer f = 321;
		Long g = 3L;
		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));

运行结果为:

true
false
true
true
true
false

前两个是因为在自动装箱时对于值从-128到127之间的值,它们被装箱为Integer对象后,会存在内存中被重用

中间两个是因为包装类的“==”运算在不遇到算数运算的情况下不会自动拆箱

后两个是因为equals()方法不处理类型的转换问题。

猜你喜欢

转载自blog.csdn.net/dear_mango/article/details/80663252