简体   繁体   English

如何在Java中定义具有长度和某些元素值的数组?

[英]How can I define an array with length and some of elements' value in Java?

I need define an array and I know the first three elements are 1,2,3 but the length of this array would be an identified num ,like 6, I will add the other elements in a method, I use 我需要定义一个数组,我知道前三个元素是1,2,3,但是此数组的长度将是一个已标识的num,例如6,我将在方法中添加其他元素,我使用

int[] a = new int[6]{1,2,3};

but eclipse tell me an error.Must I use some container like ArrayList? 但是日食告诉我一个错误。我必须使用ArrayList之类的容器吗? Can I solve it with array? 我可以用数组解决吗? Is there any way elegant rather than this 有什么办法比这优雅吗

int[] a = new int[]{1,2,3,0,0,0}

or 要么

int[] a = new int[6]

because the unknown elements or known elements may be a lot, I don't want to write them one by one. 因为未知元素或已知元素可能很多,所以我不想一个接一个地编写它们。

Java does not offer a syntax to do what you are attempting to do. Java不提供执行您要尝试执行的语法。 It requires the declared number of elements to match the number of initializers that you supply. 它要求声明的元素数量与您提供的初始化程序数量匹配。

If you would like to initialize part of an array, you can do it like this: 如果要初始化数组的一部分,可以这样进行:

int[] a = new int[16];
{
    System.arraycopy(new int[] {1,2,3}, 0, a, 0, 3);
}

You can only define an array with a fixed size. 您只能定义一个固定大小的数组。 If you provide data when creating it, you must give all fields a value. 如果在创建数据时提供数据,则必须为所有字段赋予一个值。 That's why the first piece of code is wrong and leads yout to the second one. 这就是为什么第一段代码是错误的,并导致您到达第二段代码。

Just initialize the array and put 0's for the values you don't know yet. 只需初始化数组,然后将0表示不知道的值即可。

int[] a = new int[] { 1,2,3,0,0,0 }

Or if you use Integer instead of int you can use null, but I wouldn't recommend that unless you really need null values. 或者,如果使用Integer而不是int,则可以使用null,但是除非您确实需要null值,否则我不建议您这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM