【发布时间】:2017-11-10 00:41:07
【问题描述】:
我对 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 中的内存问题,对吧?
【问题讨论】:
标签: java memory primitive-types