Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to initialize a list of variables using an array in Java?

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

like image 495
Daniel Naftalovich Avatar asked Mar 23 '23 07:03

Daniel Naftalovich


1 Answers

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.

like image 95
feralin Avatar answered Apr 18 '23 17:04

feralin