日期:2014-05-20  浏览次数:20647 次

一个java基础问题求解
Integer a = 1;
Integer b = 2;
Integer c = 3;
Integer d = 3;
Integer e = 321;
Integer f = 321;
Long g = 3L;

System.out.println(c == d);
System.out.println(e == f);
System.out.println(c == (a + b));
System.out.println(c.equals(a + b));
System.out.println(g == (a + b));
System.out.println(g.equals(a + b));

得到的每个结果都帮着解释一下。
第一个和第二个应该是取值范围的是,超过127就会是false,Integer和int的取值范围有什么不同吗?Integer的取值范围难道是byte级别的?
尽量说得详细点,多谢。

------解决方案--------------------
与“java常量池”有关,具体说不清,去google一下“java常量池”有详细解释。
------解决方案--------------------
==是判断连个值是不是完全相等,包括存储值和存放地址,而equal判断的只是存储值不判断存放地址
------解决方案--------------------
==判断的是地址值
小于128的时候他们是公用一个地址值的
大于等于128的时候对象会重生生成。
原理看Integer类的源码
有这么一段
static final Integer cache[] = new Integer[-(-128) + 127 + 1];
static {
    for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
    }