您的位置:首页 > 编程语言 > Java开发

【Java】Integer的常量池

2016-04-05 09:37 555 查看
笔试的时候遇到一个问题:

Integer i1 = 127;
Integer i2 = 127;
Integer i3 = 128;
Integer i4 = 128;
System.out.println(i1==i2);
System.out.println(i1.equals(i2));
System.out.println(i3==i4);
System.out.println(i3.equals(i4));


输出结果是true true false true

提到了==与equals的区别,第一反应是String。

String s = new String("....")是分配在堆中不同位置的,==返回false。

String s = "..."; String ss = "..." 指向池中同一个空间,然会true

equals比较的是对象的值,而==比较的是对象本体(位置)。

Integer也有区别?

附上java的源码:

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


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

static {
// high value may be configured by property
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);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
}
high = h;

cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}

private IntegerCache() {}
}
可以看出来 Integer 也有常量池 范围是 -128~127

所以在此范围内的 == 返回true,范围外的 范围false。(当然,equals全部返回true)

同样,Short Long 的常量池范围也是-128~127。

Boolean 也实现了常量池的功能。毕竟只有true和false两个值

Character的范围0~127
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: