在Java中声明数组 [英] Declaring arrays in Java

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

问题描述

看完后,我才知道,在Java中 阵列对象。阵列的名称不是实际的阵列,但只是一个参考。 new运算符在堆上创建数组并返回引用然后将其分配给数组变量(名称)新创建的数组对象。类似如下:

After reading, I came to know that, arrays in Java are objects. The name of the array is not the actual array, but just a reference. The new operator creates the array on the heap and returns the reference to the newly created array object which is then assigned to array variable (name). Something like the following:

int[] myArray = new int[5];

不过,我也用这两种类型的数组声明。

But I also used these two type of array declaration.

int[] myArray= new int[]{5,7,3};

int[] myArray= {5,7,3};

以上两者是合法的,做工精细。那么,什么是这两个,我应该何时使用它们之间的区别?

Both of the above are legal and work fine. So what's the difference between these two and when should I use them?

推荐答案

这会产生大小为5的数组,用5 null元素:

This generates an array of size 5, with 5 null elements:

int[] myArray = new int[5];

如果值是你不知道的东西在编译时,这可能是更为有用。例如。

If the values aren't something you know at compile time, this is probably more useful. E.g.

int[] myArray = new int[blah.size()];
for (int i = 0; i < blah.size() ; i++) {
  myArray[i] = getFoo(blah.get(i));
}

如果你知道时间提前的大小,你可以使用其他形式。

If you knew the size ahead of time, you could use the other form.

int[] myArray = {blah.get(0), blah.get(1), blah.get(2)};

下面是等价(编译成相同的字节code),并产生规模推断3的数组,三个元素,5,7和3。如果有固定值的设定这种形式是非常有用的或至少​​一个固定大小值的集合。

The following are equivalent (compile to the same bytecode), and generate an array with inferred size 3, with three elements, 5, 7, and 3. This form is useful if there are fixed set of values, or at least a fixed size set of values.

int[] myArray = new int[]{5,7,3};
int[] myArray = {5,7,3};

否则,你可以完成同样的事情更长的形式:

Otherwise you could accomplish the same thing with the longer form:

int[] myArray = new int[5];
myArray[0] = 5;
myArray[1] = 7;
myArray[2] = 3;

但是,这是不必要的冗长。但是,如果你不知道有多少东西有,你必须使用第一种形式。

But this is unnecessarily verbose. But if you don't know how many things there are, you have to use the first form.

这篇关于在Java中声明数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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