栈(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