publicstatic Integer valueOf(int i){ if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; returnnew Integer(i); }
如果面试官问Integer与int的区别:估计大多数人只会说道两点,Ingeter是int的包装类,int的初值为0,Ingeter的初值 为null。但是如果面试官再问一下Integer i = 1;int ii = 1; i==ii为true还是为false?估计就有一部分人答不出来了,如果再问一下其他的,估计更多的人会头脑一片混乱。
首先看代码:
static { // 缓存上界,可以通过JVM参数来配置 int h = 127; String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); if (integerCacheHighPropValue != null) { int i = parseInt(integerCacheHighPropValue); i = Math.max(i, 127); //最大的数组值是Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - (-low)); } high = h;
cache = new Integer[(high - low) + 1]; int j = low; for (int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); }
privatestaticclassShortCache{ privateShortCache(){} staticfinal Short cache[] = new Short[-(-128) + 127 + 1]; static { for(int i = 0; i < cache.length; i++) cache[i] = new Short((short)(i - 128)); } }
publicstatic Short valueOf(short s){ finalint offset = 128; int sAsInt = s; if (sAsInt >= -128 && sAsInt <= 127) { // must cache return ShortCache.cache[sAsInt + offset]; } returnnew Short(s); }
Long
privatestaticclassLongCache{ privateLongCache(){} staticfinal Long cache[] = new Long[-(-128) + 127 + 1]; static { for(int i = 0; i < cache.length; i++) cache[i] = new Long(i - 128); } }
publicstatic Long valueOf(long l){ finalint offset = 128; if (l >= -128 && l <= 127) { // will cache return LongCache.cache[(int)l + offset]; } returnnew Long(l); }
Character
privatestaticclassCharacterCache{ privateCharacterCache(){} staticfinal Character cache[] = new Character[127 + 1]; static { for (int i = 0; i < cache.length; i++) cache[i] = new Character((char)i); } }
publicstatic Character valueOf(char c){ if (c <= 127) { // must cache return CharacterCache.cache[(int)c]; } returnnew Character(c); }
示例:
publicclassAllCacheDemo{ /** * 演示JDK内部缓存 */ publicstaticvoidmain(String[] args){ Integer a = 28; Integer b = 28; println(a == b);
Byte c = 25; Byte d = 25; println(c==d);
Short p=12; Short q=12; println(p==q);
Long x=127L; Long y=127L; println(x==y);
Character m='M'; Character n='M'; println(m==n); }