Java: How 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 is working, but second line is not working.
How can I make the initialization from the second line in one single line of code?
Solution 1:
array = new int[] {1, 1, 2, 3, 5, 8};
Source: Oracle JavaDocs - Arrays
Solution 2:
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.