a 和 b 相等吗?
Integer a = 128; Integer b = 128; System.out.println("a==b -> " + (a == b));a 和 b 不相等 准确来说大小关系不确定,与 VM 的配置(sun.misc.VM)有关
==:对比的是内存地址
_ 1. 装箱:把值类型转换成引用类型
/** * 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 /** * 该方法通常应该优先于构造函数使用,因为该方法可能通过缓存频繁请求的值来获得更好的空间和时间性能 * 此方法将始终在范围为 -128 至 127 的范围内缓存值,并且可以缓存在该范围之外的其他值 */ public static Integer valueOf(int i) { //IntegerCache:见参考一 //在 -128 ~ 127 的数 if (i >= IntegerCache.low && i <= IntegerCache.high) //直接从缓冲数组中获取 return IntegerCache.cache[i + (-IntegerCache.low)]; //不在 -128 ~ 127 的数,创建一个新的 Integer 对象 return new Integer(i); }_ 2. 拆箱:把引用类型转换成值类型
public int intValue() { return value; }所以,若有两个数值相等的 Integer a 和 Integer b,它们的大小关系:
范围大小(- ∞, -128)a != b[-128, high]high < a 或 b,a != b;high >= a 或 b,a == b(high, +∞)high < a 或 b,a != b;high >= a 或 b,a == b举个栗子,int a = 128,b = 128 high 默认为 127,则 Integer:a != b; 修改 high = 128(大于 a、b 即可),则 Integer:a == b
