一道简单面试题引出的Java数据类型连环问

题目如下:
public static void main(String[] args) {Integer i1 = 100;Integer i2 = 100;Integer i3 = 150;Integer i4 = 150;System.out.println(i1 == i2);System.out.println(i3 == i4);}【一道简单面试题引出的Java数据类型连环问】你想好答案了吗?
答案是:
truefalse为什么不都是true呢?
这就需要我们看看Integer i1 = 100;执行这条语句的时候发生了什么?
当我们给一个Integer对象赋一个int值的时候,会调用Integer类的静态方法valueOf,查看jdk源码,valueOf方法内容如下:
/** * 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. * * @parami an {@code int} value. * @return an {@code Integer} instance representing {@code i}. * @since1.5 */public static Integer valueOf(int i) {assert IntegerCache.high >= 127;if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i);}从代码和注释上可以看到,这个方法是从jdk1.5之后开始添加的 。
如果整型字面量的值在-128到127之间,直接引用常量池中的Integer对象,否则new新的Integer对象 。所以上面的面试题中i1 == i2的结果是true,而i3 == i4的结果是false 。


    推荐阅读