# Integer判等的陷阱：你知道Integer内部高速缓冲区IntegerCache吗？

https://blog.csdn.net/magician_Code/article/details/51469101

public static void main(String[] args)
{
// TODO Auto-generated method stub
Integer integer1;
Integer integer2;

integer1 = new Integer(10);
integer2 = new Integer(10);
//第一次比较
System.out.println("第一次比较:"+(integer1==integer2));

//第二次比较
System.out.println("第二次比较:"+(integer1==10));

integer1 = 127;
integer2 = 127;
//第三次比较
System.out.println("第三次比较:"+(integer1==integer2));

integer1 = 128;
integer2 = 128;
//第四次比较
System.out.println("第四次比较:"+(integer1==integer2));
}

Integer integer1 = new Integer(10);
Integer integer2 = 10;

Integer integer2 = Integer.valueOf(10);

public static Integer valueOf(int paramInt)
{
if ((paramInt >= -128) && (paramInt <= IntegerCache.high)) {
return IntegerCache.cache[(paramInt + 128)];
}
return new Integer(paramInt);
}

private static class IntegerCache
{
static final int low = -128;
static final int high;
static final Integer[] cache;

private IntegerCache() {}

static
{
int i = 127;
String str = VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (str != null) {
try
{
int j = Integer.parseInt(str);
j = Math.max(j, 127);
i = Math.min(j, 2147483518);
}
catch (NumberFormatException localNumberFormatException) {}
}
high = i;
cache = new Integer[high - -128 + 1];
int k = -128;
for (int m = 0; m < cache.length; m++) {
cache[m] = new Integer(k++);
}
assert (high >= 127);
}
}
}

public static void main(String[] args)
{
// TODO Auto-generated method stub
Integer integer1;
Integer integer2;

integer1 = new Integer(10);
integer2 = new Integer(10);
//第一次比较
//System.out.println("第一次比较:"+(integer1==integer2));
if(integer1.equals(integer2))
System.out.println("第一次比较:"+true);
else
System.out.println("第一次比较:"+false);

//第二次比较
System.out.println("第二次比较:"+(integer1==10));

integer1 = 127;
integer2 = 127;
//第三次比较
//System.out.println("第三次比较:"+(integer1==integer2));
if(integer1.equals(integer2))
System.out.println("第三次比较:"+true);
else
System.out.println("第三次比较:"+false);

integer1 = 128;
integer2 = 128;
//第四次比较
//System.out.println("第四次比较:"+(integer1==integer2));
if(integer1.equals(integer2))
System.out.println("第四次比较:"+true);
else
System.out.println("第四次比较:"+false);
}

posted @ 2019-03-06 12:30  crazyYong  阅读(358)  评论(0编辑  收藏  举报