如何在java方法中将数组作为参数传递? [英] How to pass array as parameter in java method?

查看:296
本文介绍了如何在java方法中将数组作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

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

当我尝试时:

someMethod ( {myObject} );

我在Eclipse中收到错误。

I receive error in Eclipse.

但在以下时间:

someMethod ( a );

一切正常。
为什么会出现这种差异?
谢谢。

all ok. Why this difference? Thanks.

推荐答案

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

Because the { myObject } syntax is special syntactic sugar which 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.

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

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).

致电

someMethod ( new Object[] { myObject } )

如果你想在不使用变量的情况下就地定义数组,

将起作用。

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

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

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

someMethod(myObject);

这篇关于如何在java方法中将数组作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆