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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3160347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:57:22  来源:igfitidea点击:

Java: How initialize an array in Java in one line?

javaarrays

提问by Peter

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?

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

采纳答案by MikeD

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

Source: Oracle JavaDocs - Arrays

来源:Oracle JavaDocs - 数组

回答by Dolph

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 array1with new data... Mike D's answer solves that.

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