我对Java中int和Integer变量的内存分配有疑问。为了测量内存,我使用Instrumentation.getObjectSize()方法,结果两个变量的大小相同。请查看下面的代码:
ObjectSizeFetcher.java
import java.lang.instrument.Instrumentation;
public class ObjectSizeFetcher {
private static Instrumentation instrumentation;
public static void premain(String args, Instrumentation inst) {
instrumentation = inst;
}
public static long getObjectSize(Object o) {
return instrumentation.getObjectSize(o);
}
}
Test.java
public class Test {
public static void main(String[] args) throws Exception {
int i=0;
Integer i1 = new Integer(0);
long value = ObjectSizeFetcher.getObjectSize(i);
System.out.println(value);//prints 16
long value1 = ObjectSizeFetcher.getObjectSize(i1);
System.out.println(value1);//prints 16
}
}
在上述情况下,两个变量的大小打印出来是相同的。我的疑问是,int是原始类型,其大小为4字节,而Integer是引用类型,其大小为16字节,但在这种情况下,为什么两个值都产生16字节?如果它们在堆中占用相同的内存,那么这会导致Java中的内存问题,对吗?