今天打算複習一下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。
所以我們要注意自動裝箱時候數值的範圍的選擇~~