Java:如何在一行中初始化Java中的数组?

时间:2022-01-06 21:29:58
int[] array1 = {1, 2, 3, 4, 5, 6, ,7, 8}; - working


array1 = {1, 1, 1, 1, 2, 5, ,7, 8}; - NOT working

The first line is working, but second line is not working.

第一行是有效的,第二行是无效的。

How can I make the initialization from the second line in one single line of code?

如何在一行代码中从第二行进行初始化?

2 个解决方案

#1


85  

array = new int[] {1, 1, 2, 3, 5, 8};

Source: Oracle JavaDocs - Arrays

源代码:Oracle JavaDocs -数组。

#2


5  

The reason the first one works is because the compiler can check how many elements you are going to assign to the array, and then allocate the appropriate amount of memory.

第一个操作成功的原因是编译器可以检查要为数组分配多少元素,然后分配适当的内存。

EDIT: I realize now that you are just trying to update array1 with new data... Mike D's answer solves that.

编辑:我现在意识到你只是想用新的数据更新array1……Mike D的答案解决了这个问题。

#1


85  

array = new int[] {1, 1, 2, 3, 5, 8};

Source: Oracle JavaDocs - Arrays

源代码:Oracle JavaDocs -数组。

#2


5  

The reason the first one works is because the compiler can check how many elements you are going to assign to the array, and then allocate the appropriate amount of memory.

第一个操作成功的原因是编译器可以检查要为数组分配多少元素,然后分配适当的内存。

EDIT: I realize now that you are just trying to update array1 with new data... Mike D's answer solves that.

编辑:我现在意识到你只是想用新的数据更新array1……Mike D的答案解决了这个问题。