Danny King Danny King - 2 years ago 88
Java Question

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;


Answer Source


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


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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download