Is there a syntax in Java to initialize a list of variables to corresponding objects in an array?
String hello, world;
String[] array = {"hello", "world"};
//I want:
{hello, world} = array;
//instead of:
hello = array[0];
world = array[1];
I think I recall this type of convenient syntax from Matlab, but I haven't noticed a way to achieve this in Java.. This kind of syntax would help me organize my code. Specifically I would like to feed into a function an array of objects in a single argument instead of each of the array's members in multiple arguments, and then begin the code for the method by declaring variables in the method scope for named access to the array members. E.g.:
String[] array = {"hello", "world"};
method(array);
void method(array){
String {hello, world} = array;
//do stuff on variables hello, world
}
Thanks for the advice. -Daniel
Nope, there is no way to do that in Java, other than the answer you already gave, which is to initialize each variable separately.
However, you could also do something like:
String[] array = { "hello", "world" };
final int HELLO = 0, WORLD = 1;
and then use array[HELLO]
or array[WORLD]
wherever you would have used the variables. It's not a great solution, but, then again, Java usually is verbose.
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