public static void main(String[] args) {
Integer a1 = 60;//直接赋数字是一个装箱过程,等同于Integer a1 = Integer.valueOf(60)
Integer a2 = new Integer(60);
Integer a3 = Integer.valueOf(60);
int a7 = 60;
Integer a4 = 128;//直接赋数字是一个装箱过程,等同于Integer a1 = Integer.valueOf(60)
Integer a5 = new Integer(128);
Integer a6 = Integer.valueOf(128);
int a8 = 128;
System.out.println("1:" + (a1 == a2));
System.out.println("2:" + (a1 == a3));
System.out.println("3:" + (a2 == a3));
System.out.println("4:" + (a1 == a7));
System.out.println("5:" + (a2 == a7));
System.out.println("6:" + (a4 == a5));
System.out.println("7:" + (a4 == a6));
System.out.println("8:" + (a5 == a6));
System.out.println("9:" + (a5 == a8));
System.out.println("10:" + (a6 == a8));
System.out.println("11:" + (a5.intValue() == a6.intValue()));
System.out.println("12:" + a5.equals(a6));
}
//运行结果
1:false
2:true
3:false
4:true 引用类型Integer与值类型int比较比较的是值
5:true
6:false
7:false
8:false
9:true
10:true
11:true
12:true
java中Integer类型对应-128~127(jdk1.7之后,最大值可以设置,默认是127)之间的数是从缓冲区取的,所以用等号比较相等;但对于不在这区间的数字,是在堆中new出来的,地址空间不一样,也就不相等。
JDK1.6
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
private static class IntegerCache {
private IntegerCache(){}
static final Integer cache[] = new Integer[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
}
JDK1.7
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);
}
//assert关键字表示断言
1、assert <boolean表达式>
如果<boolean表达式>为true,则程序继续执行。
如果为false,则程序抛出AssertionError,并终止执行。
2、assert <boolean表达式> : <错误信息表达式>
如果<boolean表达式>为true,则程序继续执行。
如果为false,则程序抛出java.lang.AssertionError,并输入<错误信息表达式>。
/**
* 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 -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 {
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() {}
}