問題描述
我在這里有一個與 Java 相關(guān)的簡單問題.假設(shè)您有一個 int 數(shù)組作為實例變量:
I have here a simple question related to Java. Let's say you have an int array as instance variable:
int[] in = new int[5];
所以,現(xiàn)在默認情況下它包含 5 個零.但是,如果您有與局部變量相同的數(shù)組怎么辦.它是否被初始化為零?那不是家庭作業(yè),我正在學習 Java 語言.最好的問候
So, now by default it contains 5 zeros. But what if you have the same array as local variable. Does it get initialized to zeros? That is not a homework, I am learning Java language. Best regards
推薦答案
首先要了解的是,本地變量存儲在堆棧 未使用其默認值顯式初始化.而 實例變量 存儲在 Heap 中,并且默認情況下使用它們的 默認值 進行初始化.
First thing to understand is that, local varibles are stored on stack which are not initialized explicitly with their default values. While instance variables are stored on Heap, and they are by default initialized with their default value.
此外,對象也在 Heap 上創(chuàng)建,無論實例引用變量是持有其引用還是局部引用變量.
Also, objects are also created on Heap, regardless of whether an instance reference variable is holding its reference, or a local reference variable.
現(xiàn)在,當您將這樣的數(shù)組引用聲明為局部變量并使用數(shù)組對其進行初始化時,會發(fā)生什么:-
Now, what happens is, when you declare your array reference like this as local variable, and initialize it with an array: -
int[] in = new int[5];
數(shù)組引用(in)
存儲在stack上,并且為數(shù)組分配了內(nèi)存,該數(shù)組能夠在上保存5個整數(shù)元素em>heap(記住,對象是在堆上創(chuàng)建的).然后,在 Heap 上分配 5 個連續(xù)的內(nèi)存位置 (size = 5)
,用于存儲 integer 值.并且數(shù)組對象上的每個 index 都按順序保存了對這些內(nèi)存位置的 reference.然后數(shù)組引用指向該數(shù)組.因此,由于在堆上分配了 5 個整數(shù)值的內(nèi)存,因此將它們初始化為默認值.
The array reference (in)
is stored on stack, and a memory is allocated for array capable of holding 5 integer elements on heap (Remember, objects are created on Heap). Then, 5 contiguous memory location (size = 5)
, for storing integer value are allocated on Heap. And each index on array object holds a reference to those memory location in sequence. Then the array reference points to that array. So, since memory for 5 integer values are allocated on Heap, they are initialized to their default value.
而且,當你聲明你的數(shù)組引用時,不要用任何數(shù)組對象初始化它:-
And also, when you declare your array reference, and don't initialize it with any array object: -
int[] in;
數(shù)組引用是在 Stack 上創(chuàng)建的(因為它是一個局部變量),但默認情況下它不會初始化為數(shù)組,也不會初始化為 null
,與實例變量一樣.
The array reference is created on Stack (as it is a local variable), but it does not gets initialized to an array by default, and neither to null
, as is the case with instance variables.
所以,這就是使用第一種數(shù)組聲明和初始化方式時的分配方式:-
So, this is how allocation looks like when you use the first way of array declaration and initialization: -
"Your array reference"
"on stack"
| | "Array object on Heap"
+----+
| in |----------> ([0, 0, 0, 0, 0])
+----+
"Stack" "Heap"
這篇關(guān)于int 數(shù)組初始化的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!