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

求java高手解释一下Integer的等于判断,本人学习java也有一定水平,实在费解
    Integer c = 3;
    Integer d = 3;
    Integer e = 321;
    Integer f = 321;

    System.out.println(c == d);
    System.out.println(e == f);

输出 true false
    
Integer???相等 Java

------解决方案--------------------
引用
“==”比较的应该是hashcode吧,但是源码中的hashcode即value,也就是初始化时的int值;为什么大于128的就会new Integer呢
 javap指令怎么用? 

static final Integer cache[] = new Integer[-(-128) + 127 + 1];

static {
    for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
    }
这是源码中的,也就是说cache中已有-128到127,不在这范围的会新new ,这时可以理解比较是内存地址,也就是是不是同一对象,并不是比较hashCode,hashcode相同对象不一样相同,毕竟hashcode是int大小是有限的,看来lz的==,equal,hashcode什么的还有待提高哈。。
------解决方案--------------------
引用:
 public void setLocation(int x, int y) {
 
this.x = x;
this.y = y;
}




<1>.

private static void modifyPoint(Point p1, Point p2)
{
   /* Point tmpPoint = p1;
    p1 = p2;
    p2 = tmpPoint;*/
    p1.setLocation(5, 5);
    p2 = new Point(5, 5);
}


结果是[5,5], [0,0]



<2>.

private static void modifyPoint(Point p1, Point p2)
{
    Point tmpPoint = p1;
    p1 = p2;
    p2 = tmpPoint;
    p1.setLocation(5, 5);
    p2 = new Point(5, 5);