关于Integer i1 = 100; Integer i2 = 100; Integer i3 = 127; Integer i4 = 127;

时间:2025-04-28 08:10:40
public class Person {
	public static void main(String a[]) {
		Integer i1 = 100;
		Integer i2 = 100;
		Integer i3 = 127;
		Integer i4 = 127;
		(i1 == i2);
		(i3 == i4);
	}
}

在int的的包装类型Integer里面存在这个方法,当Integer大于默认的[-128,127]的时候就会new一个新对象,所以每次的引用地址都不同,所以才会出现不等于,至于这方法存在的原因有的说是对于这个范围内的数字一般使用的比较多,而不需要在常量池中new,直接栈向堆的引用过程。

     * 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
     */
    @HotSpotIntrinsicCandidate
    public static Integer valueOf(int i) {
        if (i >=  && i <= )
            return [i + (-)];
        return new Integer(i);
    }

在long中也存在这样一个

    @HotSpotIntrinsicCandidate
    public static Long valueOf(long l) {
        final int offset = 128;
        if (l >= -128 && l <= 127) { // will cache
            return [(int)l + offset];
        }
        return new Long(l);
    }