关于Integer i1 = 100; Integer i2 = 100; Integer i3 = 127; Integer i4 = 127; System.out.println

public class Person {public static void main(String a[]) {Integer i1 = 100;Integer i2 = 100;Integer i3 = 127;Integer i4 = 127;System.out.println(i1 == i2);System.out.println(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*/@HotSpotIntrinsicCandidatepublic static Integer valueOf(int i) {if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i);}

在long中也存在这样一个

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


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部