现在的位置: 首页 > 综合 > 正文

浅究 Java 中的 Integer

2013年10月01日 ⁄ 综合 ⁄ 共 714字 ⁄ 字号 评论关闭

先看代码:

public class Test {
	public static void main(String[] args) {
		Integer x = new Integer(125);
		Integer y = new Integer(125);
		System.out.println(x == y);//new了两个对象,false
		
		Integer a = 100;  
        Integer b = 100;  
        System.out.println(a == b);//返回的是同一个对象,true
        
        Integer c = 128;
        Integer d = 128;
        System.out.println(c == d);//new了两个对象,false
	}
}

再看断点调试结果:

x和y分别用了new,很明显new了两个对象。结果有id可以看得出。

a和b的值大于等于-128小于等于127,所以系统返回的是同一个对象,id都是25可以看出。

注意:a和b都是指向一个对象,如果这样:

int a = 100;
int b = 100;

那么a和b都没有指向任何对象,只是在栈中的一个字面值。

c和d大于127,所以分别new了两个对象。

因为 Integer c = 128; 实际上是执行了 Integer c = Integer.valueOf(128);

源代码是这样的:

public static Integer valueOf(int i) {
        if(i >= -128 && i <= IntegerCache.high)
            return IntegerCache.cache[i + 128];
        else
            return new Integer(i);
    }

意思就是范围-128 < i < 127的话就返回缓存对象,否则new一个新的。

IntegerCache.high默认是127,可以通过配置文件修改。

抱歉!评论已关闭.