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

Is there any syntax in Java to initialize a list of variables for the 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 remember this type of convenient syntax from Matlab, but I did not notice a way to achieve this in Java. Such syntax will help me organize my code. In particular, I would like to pass an array of objects in one argument to the function instead of each of the array members in several arguments, and then start the code for the method by declaring variables in the method area for named access to the elements of the array, For example :.

 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
source share
2 answers

No, in Java there is no way to do this, except for the answer that you have already given to initialize each variable separately.

However, you can also do something like:

 String[] array = { "hello", "world" }; final int HELLO = 0, WORLD = 1; 

and then use array[HELLO] or array[WORLD] , wherever you use variables. This is not a great solution, but, again, Java is usually verbose.

+7
source

In particular, I would like to pass an array of objects in a function in one argument instead of each of the array elements into several arguments

This is similar to the case when you should use an object instead of an array. In particular, since in your example it seems that you are 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 } 
0
source

Source: https://habr.com/ru/post/1489557/


All Articles