问题描述
在此示例中,任何人都可以解释在内存方面(堆栈和堆)会发生什么情况?如果我正确理解,java会将对象存储在堆上,因此i1将在堆上...与字符串相同吗?但是i2呢,考虑到它是一个类字段声明.
Anyone could explain what happens memory wise (Stack & Heap) in this example? If I understand it correctly, java stores objects on the heap, so i1 will be on the heap... same with string? But what about i2, considering it is a class field declaration.
public ExampleClass {
Integer i1=new Integer(1);
int i2 = 2;
String str = "abc";
}
推荐答案
在您拥有诸如new ExampleClass()
之类的代码之前,什么都不会发生.完成此操作后,将在堆上分配一个新对象.其中将包括对i1
,i2
和str
的引用.我猜想因为您不在使用方法中,所以i2
会在后台自动转换为等效于Integer i2 = new Integer(0)
的形式.所有这三个引用都将指向同样也在堆上分配的对象.请注意,字符串是不可变的,因此,如果已有String
且值为"abc"
,则引用可能指向该字符串.
Nothing happens until you have some code like new ExampleClass()
. Once you do that, a new object is allocated on the heap. Included in that will be references to i1
, i2
, and str
. I'm guessing that since you're not in a method, that i2
will be automatically converted behind the scenes to the equivalent of Integer i2 = new Integer(0)
. All 3 of these references will be pointing to objects also allocated on the heap. Note that strings are immutable so if there is already a String
with the value "abc"
, then the reference may point to that.
这篇关于Java(Stack& Heap)-在这个简单的示例中,明智地执行内存操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!