眾所周知:java中Integer有一個常量池范圍-128~127
Integer a = 500, b = 500; System.out.println(a == b);//false a = 100; b = 100; System.out.println(a == b);//true
相信也有一部分人在面試時,也被問到過這個問題,但是如果面試官繼續追問:如果我想讓
Integer a = 500, b = 500; System.out.println(a == b);
也返回true,該怎么做?沒准備的同學,可能會一時被問住,其實答案就在java.lang.Integer.IntegerCache 這個類的源碼上
/** * Cache to support the object identity semantics of autoboxing for values between * -128 and 127 (inclusive) as required by JLS. * * The cache is initialized on first usage. The size of the cache * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option. * During VM initialization, java.lang.Integer.IntegerCache.high property * may be set and saved in the private system properties in the * sun.misc.VM class. */ private static class IntegerCache { // ... }
這個類的注釋上,已經明細說明:
-XX:AutoBoxCacheMax=<size> -Djava.lang.Integer.IntegerCache.high=<size>
這2個參數都可以控制上限。