我在这里有一个与 Java 相关的简单问题.假设您有一个 int 数组作为实例变量:
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];
所以,现在默认情况下它包含 5 个零.但是,如果您有与局部变量相同的数组怎么办.它是否被初始化为零?那不是家庭作业,我正在学习 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 上创建,无论实例引用变量是持有其引用还是局部引用变量.
Also, objects are also created on Heap, regardless of whether an instance reference variable is holding its reference, or a local reference variable.
现在,当您将这样的数组引用声明为局部变量并使用数组对其进行初始化时,会发生什么:-
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];
数组引用(in)
存储在stack上,并且为数组分配了内存,该数组能够在上保存5个整数元素em>heap(记住,对象是在堆上创建的).然后,在 Heap 上分配 5 个连续的内存位置 (size = 5)
,用于存储 integer 值.并且数组对象上的每个 index 都按顺序保存了对这些内存位置的 reference.然后数组引用指向该数组.因此,由于在堆上分配了 5 个整数值的内存,因此将它们初始化为默认值.
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.
而且,当你声明你的数组引用时,不要用任何数组对象初始化它:-
And also, when you declare your array reference, and don't initialize it with any array object: -
int[] in;
数组引用是在 Stack 上创建的(因为它是一个局部变量),但默认情况下它不会初始化为数组,也不会初始化为 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.
所以,这就是使用第一种数组声明和初始化方式时的分配方式:-
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"
这篇关于int 数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!