4

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

4
  • The answer is no. You could write a method to do this, passing in declared variables of mutable objects (ie. not for strings) and an array. Commented Jul 3, 2013 at 17:43
  • I'm confused what you mean. Why can't you pass the array and assign variables to the indices of the array? Commented Jul 3, 2013 at 17:44
  • 1
    @MarcoCorona the OP is asking about a nicer (syntactically) way to do that. Commented Jul 3, 2013 at 17:47
  • Thanks for the answer and idea. The mutable objects method is probably more of a hassle for me than just using indexes on the arrays.. Commented Jul 3, 2013 at 17:51

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.