今天打算复习一下Java基础,之前学的太快速了,现在暑假,好好把那些细节看一下
复习到自动装箱和自动拆箱的时候,这里有个很有趣的现象
- Integer n1 = 100;
- Integer n2 = 100;
- System.out.println(n1 == n2);
- Integer n3 = 200;
- Integer n4 = 200;
- System.out.println(n3 == n4);
你们猜猜结果是什么 第一个是true,第二个是false。有趣吧。
其实它们是相当于
- Integer n1 = Integer.valueOf(100);
- Integer n2 = Integer.valueOf(100);
- System.out.println(n1 == n2);
- Integer n1 = Integer.valueOf(200);
- Integer n2 = Integer.valueOf(200);
- System.out.println(n1 == n2);
所以那个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.
- *
- * @param i an {@code int} value.
- * @return an {@code Integer} instance representing {@code i}.
- * @since 1.5
- */
- public static Integer valueOf(int i) {
- assert IntegerCache.high >= 127;
- if (i >= IntegerCache.lo&&i<=IntegerCache.high)
- return IntegerCache.cache[i + (-IntegerCache.low)];
- return new Integer(i);
- }
所以我们知道了,对于-128到127之间的数,Integer.valueOf(99)返回的是缓存中的对象,所以两次调用valueOf返回的是同一个对象,故结果是true.而Integer.valueOf(199)返回的则是重新实例化的对象,故结果是false.
自动拆箱
- Integer n1 = 10;
- int t1 = n1;
- Integer n2 = 10;
- int t2 = n2;
- System.out.println(t1 == t2);
- Integer n1 = 199;
- int t1 = n1;
- Integer n2 = 199;
- int t2 = n2;
- System.out.println(t1 == t2);
两次的结果是true。
所以我们要注意自动装箱时候数值的范围的选择~~