栈(stack)与堆(heap)都是Java用来在Ram(随机访问存储器,内存)中存放数据的地方。栈(stack):存取速度比堆要快(句柄置放地)。堆(heap):对象置放地。int a = 3;
int b = 3;
Integer c = new Integer(3);System.out.println(a == b);
System.out.println(a == c);按道理说,变量b指向的是stack空间里面开辟的3,而c的引用应该是new Integer(3)这个对象,而对象应该放在heap空间里。两个完全不同的引用。为啥System.out.println(a == c);的结果是TRUE呢???各位大神帮忙解释下。

解决方案 »

  1.   

    楼主能发散思维真的很不错的。因为你上面的“==”是比较地址的。
    package csdn.programbbs_625;public class TextHeapStack {
    public static void main(String[] args) {
    int a = 3;
    int b = 3;
    Integer c = new Integer(3);
    Integer d = new Integer(3); System.out.println(a == c);
    System.out.println(d == c);
    }
    }
      

  2.   

    楼上正解。JVM会自动拆箱,调用Integer类的intValue方法。
    源码:public class Test{

    public static void main(String[] args){
    int a = 3;
    Integer c = new Integer(3);

    boolean d = (a==c);
    }
    }
    使用JAVAP查看编译后文件:  public static void main(java.lang.String[]);
        flags: ACC_PUBLIC, ACC_STATIC
        Code:
          stack=3, locals=4, args_size=1
             0: iconst_3
             1: istore_1
             2: new           #2                  // class java/lang/Integer
             5: dup
             6: iconst_3
             7: invokespecial #3                  // Method java/lang/Integer."<init
    >":(I)V
            10: astore_2
            11: iload_1
            12: aload_2
            13: invokevirtual #4                  // Method java/lang/Integer.intVal
    ue:()I
            16: if_icmpne     23
            19: iconst_1
            20: goto          24
            23: iconst_0
            24: istore_3
            25: return
          LineNumberTable:
            line 4: 0
            line 5: 2
            line 7: 11
            line 8: 25
      

  3.   

    呵呵,JVM自动拆箱,拆箱之后,就不是对象而是基本数据类型了。现在完全明白了!