[Java]Integer和String的构造函数问题
public class test {
public static void main(String[] agrs) {
int a = 1000, b = 1000;
System.out.println(a == b); // true
Integer c = 1000, d = 1000;
System.out.println(c == d); // false
Integer e = 100, f = 100;
System.out.println(e == f); // true
}
}
答案:
来看JAVA源代码中Integer的构造函数:
JDK1.5开始,Integer对象的赋值会自动调用Integer类的valueOf(int i)方法
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) {
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
而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.5开始,为了增强一系列基础类型对应对象的性能,JVM预缓存一部分常量,例如Integer预缓存-128~127这些数(实际上是一个 byte所能表示的范围),如果赋值数在此范围内,对象直接指向预缓存地址,如果不在,重新赋值(所以造成地址不同)。
验证代码:
for (int i = -200; i < 200; i++) {
Integer a = i, b = i;
System.out.print(i + " ");
System.out.println(a == b);
}
结果:i为-128到127时,结果为true。
类似的问题还有几个月前让我很疑惑的字符串构造问题:
class test {
public static void main(String[] agrs) {
String a = "Hello";
String b = "Hello";
System.out.println(a == b); //true
String c = new String("Hello");
String d = new String("Hello");
System.out.println(c == d); //false
}
}
这个则是和静态常量池有关了。
要学的还有很多。
没有评论 »
RSS feed for comments on this post. TrackBack URL