int数组初始化 [英] int array initialization

查看:26
本文介绍了int数组初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有一个与 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

推荐答案

首先要理解的是,局部变量存储在堆栈 未使用其默认值显式初始化.而实例变量存储在中,并且默认使用默认值进行初始化.

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.

此外,对象也在上创建,无论是实例引用变量持有其引用,还是局部引用变量.

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)存储在上,并为能够容纳5个整数元素的数组分配内存em>heap(记住,对象是在 Heap 上创建的).然后,在上分配5个连续的内存位置(size = 5),用于存储整数值.数组对象上的每个索引都按顺序保存对这些内存位置的引用.然后数组引用指向该数组.因此,由于 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数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆