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

查看:140
本文介绍了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];

数组引用(中)存储在的的和存储器分配给可容纳的 5整数数组的元素上的的(记住,对堆创建对象)。然后,5个连续内存位置(大小= 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;

阵列基准上的堆叠的(因为它是一个局部变量),但它不被初始化为默认的阵列,并且既不,如与实例变量的情况。

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天全站免登陆