对于包装类中的整形包装类,Byte、Short、Integer、Long等,对于数值在-128到127的内容会在堆中创建缓存,比如拿Integer举例,Integer a = 10,Integer b =10,
10对应在缓存数组CACHE[138],所以a == b是比较的就是CACHE[138]对应的地址,显然两者地址是相同的。对应源码如下
public static Integer valueOf(int i) {
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 {
// high value may be configured by property
int h = 127;
}
}
对于包装类,new一个包装类就会创建一个新的对象,然后将原本的引用地址覆盖为新的引用地址。所以String Integer是线程安全的。