views:

325

answers:

6

Hello,

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!

+1  A: 
values = new float[] { 0.1f, 0.2f, 0.3f };
bmargulies
+5  A: 

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:

float[] values = new float[3];
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?

skaffman
I think this might be it, 10.6 Array Initializers, http://java.sun.com/docs/books/jls/third_edition/html/arrays.html#11358
Adrian
This seems to be the relevant part of the grammar: http://java.sun.com/docs/books/jls/third_edition/html/arrays.html#11358 - Personally, I've always found the java language spec to be very readable, compared with similar documents.
Michael Borgwardt
You may want to note that the bottom code creates a new array.
Matthew Flaschen
+2  A: 

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 field. If values was the only reference to an already existing field, it becomes eligible for garbage collection.

Julian Lettner
+2  A: 

If you know the values at compile time you can do :

float[] values = {0.1f, 0.2f, 0.3f};

There is no way to do that if values are variables in runtime.

fastcodejava
A: 

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. But either way, the initializer is initializing a new array object, not updating an existing one.

Stephen C
A: 

This should work, but is slower and feels wrong: System.arraycopy(new float[]{...}, 0, values, 0, 3);

Bart van Heukelom