Daniel Naftalovich
Daniel Naftalovich

Reputation: 335

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

Upvotes: 4

Views: 744

Answers (2)

DannyMo
DannyMo

Reputation: 11984

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

This seems like a case where you should be using an object instead of an array. Specifically because in your example it seems like you're using an array to represent an object with two fields, hello and world:

class Parameters {
  String hello;
  String world;

  public Parameters(String hello, String world) {
    this.hello = hello;
    this.world = world;
  }
}

//...
Parameters params = new Parameters("hello", "world");
method(params);
//...

void method(Parameters params) {
  // do stuff with params.hello and params.world
}

Upvotes: 0

feralin
feralin

Reputation: 3408

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.

Upvotes: 7

Related Questions