문제

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

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

but eclipse tell me an error.Must I use some container like 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. 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.

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top