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?
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.
List<String> list = List. of("foo", "bar", "baz"); Set<String> set = Set. of("foo", "bar", "baz");
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.
array = new int[] {1, 1, 2, 3, 5, 8};
Source: Oracle JavaDocs - Arrays
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With