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

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 works, but the second line does not work.

How can I initialize from the second line in one line of code?

+41
java arrays
Jul 01 '10 at 17:50
source share
2 answers
 array = new int[] {1, 1, 2, 3, 5, 8}; 

Source: Oracle JavaDocs - Arrays

+79
Jul 01 '10 at 17:52
source share

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: Now I understand that you are just trying to update array1 with new data ... Mike D's answer solves this.

+4
Jul 01 '10 at 17:53
source share



All Articles