Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arrays

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?

like image 756
Peter Avatar asked Jul 01 '10 17:07

Peter


People also ask

How do you declare and initialize an array in a single line?

We can declare and initialize arrays in Java by using a new operator with an array initializer. Here's the syntax: Type[] arr = new Type[] { comma separated values }; For example, the following code creates a primitive integer array of size 5 using a new operator and array initializer.

How do you initialize a list in one line in Java?

List<String> list = List. of("foo", "bar", "baz"); Set<String> set = Set. of("foo", "bar", "baz");

How do you initialize an entire array in 1?

Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.


2 Answers

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

Source: Oracle JavaDocs - Arrays

like image 66
MikeD Avatar answered Sep 18 '22 15:09

MikeD


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.

like image 41
Dolph Avatar answered Sep 18 '22 15:09

Dolph