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

查看:194
本文介绍了如何在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天全站免登陆