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

JavaArrays

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Source: Oracle JavaDocs - Arrays

Solution 2 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeterView Question on Stackoverflow
Solution 1 - JavaMikeDView Answer on Stackoverflow
Solution 2 - JavaDolphView Answer on Stackoverflow