I have a Java array defined already e.g.
float[] values = new float[3];
I would like to do something like this further on in the code:
values = {0.1f, 0.2f, 0.3f};
But that gives me a compile error. Is there a nicer way to define multiple values at once, rather than doing this?:
values[0] = 0.1f; values[1] = 0.2f; values[2] = 0.3f;
Thanks!
Java does not provide a construct that will assign of multiple values to an existing array's elements. The initializer syntaxes can ONLY be used when creation a new array object. This can be at the point of declaration, or later on.
Declaring and Assigning Variables You can also assign multiple variables to one value: a = b = c = 5; This code will set c to 5 and then set b to the value of c and finally a to the value of b .
To store multiple values, there are two ways of carrying out the task. One way is to assign each value to a single variable, and the other, much more efficient way, is to assign multiple values to a single variable. That is what we call an array. An array is a way to store multiple values in a single variable.
We declare an array in Java as we do other variables, by providing a type and name: int[] myArray; To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15};
Yes:
float[] values = {0.1f, 0.2f, 0.3f};
This syntax is only permissible in an initializer. You cannot use it in an assignment, where the following is the best you can do:
values = new float[3];
or
values = new float[] {0.1f, 0.2f, 0.3f};
Trying to find a reference in the language spec for this, but it's as unreadable as ever. Anyone else find one?
On declaration you can do the following.
float[] values = {0.1f, 0.2f, 0.3f};
When the field is already defined, try this.
values = new float[] {0.1f, 0.2f, 0.3f};
Be aware that also the second version creates a new array. If values
was the only reference to an already existing field, it becomes eligible for garbage collection.
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