用Java声明数组

阅读之后,我才知道, arrays in Java中的arrays in Java是对象。 数组的名称不是实际的数组,而只是一个引用。 new运算符在堆上创建数组,并返回对新创建的数组对象的引用,然后将其分配给数组变量(name)。 类似于以下内容:

 int[] myArray = new int[5]; 

但我也使用了这两种类型的数组声明。

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

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

以上两种都是合法的,工作正常。 那么这两者之间有什么区别呢?我应该何时使用它们?

这将生成一个大小为5的数组,其中包含5个null元素:

 int[] myArray = new int[5]; 

如果值不是您在编译时知道的值,那么这可能更有用。 例如

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

如果您提前知道尺寸,可以使用其他forms。

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

以下是等效的(编译为相同的字节码),并生成一个推断大小为3的数组,其中包含三个元素5,7和3.如果有固定的值集,或者至少是固定大小,则此forms很有用一组价值观。

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

否则你可以用更长的forms完成同样的事情:

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

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

请关注评论

 int[] myArray = new int[5]; //memory allocated for 5 integers with nulls as values int[] myArray= new int[]{5,7,3}; //memory allocated for 3 integers with values int[] myArray= {5,7,3}; // same as above with different syntax memory allocated for 3integers with values. 

第二种和第三种风格之间的差异。

  someX(new int[] {1,2,3}); // inline creation array style someX(declaredArray); // using some declared array someX({1,2,3}); //Error. Sorry boss, I don't know the type of array private void someX(int[] param){ // do something } 

根据两种情况的字节码,没有区别。 在这两种情况下,分配了3个长度空间并分配了值。

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

 public class array.ArrayTest { public array.ArrayTest(); Code: 0: aload_0 1: invokespecial #8 // ()V 4: return public static void main(java.lang.String[]); Code: 0: iconst_3 1: newarray int 3: dup 4: iconst_0 5: iconst_5 6: iastore 7: dup 8: iconst_1 9: bipush 7 11: iastore 12: dup 13: iconst_2 14: iconst_3 15: iastore 16: astore_1 17: return } 

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

 public class array.ArrayTest { public array.ArrayTest(); Code: 0: aload_0 1: invokespecial #8 // ()V 4: return public static void main(java.lang.String[]); Code: 0: iconst_3 1: newarray int 3: dup 4: iconst_0 5: iconst_5 6: iastore 7: dup 8: iconst_1 9: bipush 7 11: iastore 12: dup 13: iconst_2 14: iconst_3 15: iastore 16: astore_1 17: return } 
 int[] myArray = new int[5]; 

在这里我们指定数组的长度为5

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

在这里我们传递三个元素,然后指定长度为3。

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

在这里,我们传递将自动指定长度为3的元素。