Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有一种方法可以在Java中使用数组初始化变量列表?_Java_Arrays_List_Syntax_Initialization - Fatal编程技术网

有没有一种方法可以在Java中使用数组初始化变量列表?

有没有一种方法可以在Java中使用数组初始化变量列表?,java,arrays,list,syntax,initialization,Java,Arrays,List,Syntax,Initialization,Java中是否有将变量列表初始化为数组中相应对象的语法 String hello, world; String[] array = {"hello", "world"}; //I want: {hello, world} = array; //instead of: hello = array[0]; world = array[1]; 我想我还记得Matlab中的这种方便语法,但我还没有注意到用Java实现这种语法的方法。。这种语法可以帮助我组织代码。具体地说,我希望将单个参数中的对象数

Java中是否有将变量列表初始化为数组中相应对象的语法

String hello, world;
String[] array = {"hello", "world"};

//I want:
{hello, world} = array;

//instead of:
hello = array[0];
world = array[1];
我想我还记得Matlab中的这种方便语法,但我还没有注意到用Java实现这种语法的方法。。这种语法可以帮助我组织代码。具体地说,我希望将单个参数中的对象数组(而不是多个参数中的每个数组成员)馈送到函数中,然后通过在方法范围中声明变量来开始该方法的代码,以便对数组成员进行命名访问。例如:

String[] array = {"hello", "world"};

method(array);

void method(array){
   String {hello, world} = array;
   //do stuff on variables hello, world
}

谢谢你的建议-Daniel

不,在Java中没有办法做到这一点,除了您已经给出的答案,即分别初始化每个变量

但是,您也可以执行以下操作:

String[] array = { "hello", "world" };
final int HELLO = 0, WORLD = 1;
然后使用
array[HELLO]
array[WORLD]
无论您在哪里使用变量。这不是一个很好的解决方案,但是,Java通常是冗长的

具体地说,我想将一个对象数组输入到函数中 在单个参数中,而不是在 多参数

在这种情况下,您应该使用对象而不是数组。特别是因为在您的示例中,似乎使用数组来表示具有两个字段的对象,
hello
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
}

答案是否定的。你可以写一个方法来实现这一点,传递可变对象的声明变量(即不是字符串)和数组。我不明白你的意思。为什么你不能传递数组并将变量分配给数组的索引?@MarcoCorona OP正在询问一种更好的(语法上的)方法。谢谢你的回答和想法。对于我来说,可变对象方法可能比在数组上使用索引更麻烦。@DanielNaftalovich没问题!