自动拆箱、装箱
拆箱的情况
- 调用
intValue()
- 与基本类型做算术运算和==时
装箱情况
-
直接赋值都会装箱调用
valueOf()
- Integer i =4;
-
源码
public class tt { public static void main(String[] args) { int i = 3; int a = 1; Integer b = 2; Integer c = 3; Integer d = 3; Integer e = 321; Integer f = 321; Long g = 3l; System.out.println(i == c); 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)); } }
-
反编译后借用网上老哥的反编译截图
-
return
了一个新对象,IntegerCache.cache
数组中的-128-127是在常量池(静态常量池)中的。/** * Returns an {@code Integer} instance representing the specified * {@code int} value. If a new {@code Integer} instance is not * required, this method should generally be used in preference to * the constructor {@link #Integer(int)}, as this method is likely * to yield significantly better space and time performance by * caching frequently requested values. * * This method will always cache values in the range -128 to 127, * inclusive, and may cache other values outside of this range. * * @param i an {@code int} value. * @return an {@code Integer} instance representing {@code i}. * @since 1.5 */ public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
-
包装类的“==”运算在遇到算术运算的情况下会自动拆箱
System.out.println(g == (a + b));
//true- 自动拆箱了
评论区