int和Integer的区别
int和Integer的区别
点击查看示例
public class Test01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a=100;
int b=100;
int c=200;
int d=200;
Integer x=100;
Integer y=100;
Integer o=200;
Integer p=200;
System.out.println(a==b);
System.out.println(c==d);
System.out.println(x==y);
System.out.println(o==p);
System.out.println(a==x);
System.out.println(c==o);
}
}
结果为
true
true
true
false
true
true
原因:
在Integer的底层源码里
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) {
try {
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);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
当Integer中定义的值处在-128到127之间时,比较数字的大小
如果不在这个区间内,Integer则会new一个对象
因为Integer o=200
而且200>127
所以会new Integer o;
同理,p也是
而当对象作比较的话比较的是地址,new出来的o,和new出来的p地址不一样
new的Integer对象的地址不一样,所以为false