2013-05-20 15:37:07.0|分类: java|浏览量: 2298
|
Integer这个家伙,使用==比较的时候,有时候为true,有时候是false。这是为什么?终于有一天,研究研究为什么这样,简单的例子: package com.java.jvm;
public class IntegerTest {
/**
* @param args
*/
public static void main(String[] args) {
compare(10,10);//true
compare(128,128);//false
// Integer a = 10;
// System.out.println(a.hashCode());
// Integer b = 10;
// System.out.println(b.hashCode());
// compare(a,10);//true
// compare(a,b );//true
// a = 128;
// b = 128;
// compare(a,128); //false
// compare(a,b); //false
}
public static void compare(Integer a , Integer b){
System.out.println(a==b);
}
} = =操作符比较的是操作符两端的操作数是否是同一个对象;另外= =操作符两边的操作数必须是同一类型的(可以是父子类之间)
= =比较的是地址。 那就说明上面Interger=10的对象地址相同,而Integer=128的对象地址不相同,这是怎么发生的呢?,Integer的源码: 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);
}
}
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);
}
valueOf(int i)返回一个表示指定的 int 值的 Integer 实例。如果不需要新的 Integer 实例,则通常应优先使用该方法,而不是构造方法 Integer(int),因为该方法有可能通过缓存经常请求的值而显著提高空间和时间性能。 Integer中IntegerCache有一个静态的Integer数组,在类加载时就将-128 到 127 的Integer对象创建了,并保存在cache数组中,一旦程序调用valueOf 方法,如果i的值是在-128 到 127 之间就直接在cache缓存数组中去取Integer对象。 原因找到了,现在看看其他的类型: Boolean(全部缓存) Byte(全部缓存) Double(没有缓存) Long(-128-127缓存) Character(c <= 127 缓存) Short(-128-127缓存) |
