java 如何在java方法中将数组作为参数传递?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11332535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:41:23  来源:igfitidea点击:

How to pass array as parameter in java method?

javaarraysmethodsparameters

提问by user710818

Code:

代码:

Object[] a={ myObject};
someMethod(Object ...arg);

when I try:

当我尝试:

someMethod ( {myObject} );

I receive error in Eclipse.

我在 Eclipse 中收到错误。

but when:

但当:

someMethod ( a );

all ok. Why this difference? Thanks.

一切都好。为什么会有这种差异?谢谢。

回答by Andrzej Doyle

Because the { myObject }syntax is special syntactic sugarwhich only applies when you're initialising an array variable. This is because on its own the assignment lacks type information; but in the special case of assignment the type is fully inferred from the variable.

因为{ myObject }语法是特殊的语法糖,仅在初始化数组变量时才适用。这是因为赋值本身缺少类型信息;但在赋值的特殊情况下,类型是从变量中完全推断出来的。

In the first example, the compiler knows you're assigning to a(which is an Object[]), so this syntax is allowed. In the latter you aren't initialising a variable (and due to a weakness in Java's type inference, it won't even fully work out the context of the parameter assignment either). So it wouldn't know what type the array should be, even if it could unambiguously determine that that's what you're trying to do (as opposed to e.g. declaring a block).

在第一个示例中,编译器知道您要分配给a(即Object[]),因此允许使用此语法。在后者中,您没有初始化变量(并且由于 Java 类型推断的弱点,它甚至无法完全计算出参数分配的上下文)。所以它不知道数组应该是什么类型,即使它可以明确地确定这就是你想要做的(而不是例如声明一个块)。

Calling

打电话

someMethod ( new Object[] { myObject } )

would work if you want to define the array in-place without using a variable.

如果您想在不使用变量的情况下就地定义数组,将会起作用。



While the above answers your question as asked, I notice that the method you're calling is varargsrather than explicitly requiring an array paramter. So in this case you could simply call

虽然以上回答了您的问题,但我注意到您调用的方法是varargs而不是明确要求数组参数。所以在这种情况下,你可以简单地调用

someMethod(myObject);

回答by user710818

someMethod(new Object[] { "" });

Should do the trick!

应该做的伎俩!