读书人

STACK和HEAP的有关问题

发布时间: 2013-07-01 12:33:04 作者: rapoo

STACK和HEAP的问题
栈(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呢???各位大神帮忙解释下。
[解决办法]
自动装箱,拆箱。
[解决办法]
楼主能发散思维真的很不错的。因为你上面的“==”是比较地址的。
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);
}
}


[解决办法]
楼上正解。

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

读书人网 >J2SE开发

热点推荐