int a = 128;
Integer b = 128;
Integer c = 128;
Integer d = new Integer(128);
System.out.println(a==b);
System.out.println(a==c);
System.out.println(a==d);
System.out.println(b==c);
System.out.println(b==d);
System.out.println(c==d);
答案:
true
true
true
true
false
false
falseint a = 12;
Integer b = 12;
Integer c = 12;
Integer d = new Integer(12);
System.out.println(a==b);
System.out.println(a==c);
System.out.println(a==d);
System.out.println(b==c);
System.out.println(b==d);
System.out.println(c==d);
答案:
true
true
true
true
false
false谁能解释下为什么有这样的结果?

解决方案 »

  1.   

    第一个答案多了一个true,需要去掉
      

  2.   

    数字超过127似乎Integer会new出一个Integer,为什么会这样?
    new出来的对象不是放在堆中么,为什么会与int的地址相同,
    最不明白就是2个new出的Integer 与int相等,而这两个Integer却不相等。
    谁能告诉我具体是怎么样的
      

  3.   

    当你拿一个int类型和Integer类型比较时,系统会自动根据你写的顺序自动装箱/解箱
    比如 int == Integer 系统会自动取Integer类型的int值来和前面的int比较
    当 Integer == int 时,系统将自动将int类型包装成Integer对象来比较地址
    这时我的理解.....
    当Integer小于128时使用的Integer是常量,只有当包装的int值大于等于128时系统才分配新的对象
    这时java的性能优化。
    其它包装类也类似
      

  4.   

    http://blog.csdn.net/ZangXT/archive/2008/11/19/3334030.aspx
      

  5.   

    要完全明白这个问题,你要了解java中的内存机制
    栈  堆  池
    找一些资料看看,<<java核心技术>>有详细的说明,看一下吧
      

  6.   

    int a = 128; 
    Integer b = 128; 
    Integer c = 128; 
    Integer d = new Integer(128); 
    System.out.println(a==b); 
    System.out.println(a==c); 
    System.out.println(a==d); 
    System.out.println(b==c); //这里是false
    System.out.println(b==d); 
    System.out.println(c==d);
      

  7.   


    还有一点比较有意思,<Java Puzzlers>一书里的一个例子: 
           请提供i1和i2的声明,(i1!=i2)&&(i1<=i2)&&(i1>=i2)为true。
           看到i1<=i2 并且i1>=i2都成立,我们自然的想法就是i1==i2,但是java中的autoboxing和auto-unboxing破坏了这点。
           看这个声明: 
          Integer i1=new Integer(0);
          Integer i2=new Integer(0);
          那么i1>=i2和i1<=i2都是true,因为使用>=和<=的时候会进行auto-unboxing操作,实际比较的是i1和i2auto-unboxing之后的基本类型值,因此这两个都是true,而i1和i2明显指向的不是同一个对象,所以i1!=i2也是true。
    这个很有意思