Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java array assignment (multiple values)

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!

like image 305
Danny King Avatar asked Apr 04 '10 21:04

Danny King


People also ask

How do you assign multiple values to an array in Java?

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.

How do you assign multiple values to multiple variables in Java?

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 .

How do you store multiple values in an array?

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.

How do you assign values to an array in Java?

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};


2 Answers

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?

like image 61
skaffman Avatar answered Oct 14 '22 22:10

skaffman


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.

like image 27
Julian Lettner Avatar answered Oct 14 '22 23:10

Julian Lettner