简体   繁体   English

将Array作为参数传递给{}

[英]Passing Array as argument in form {}

I can set an array like this: 我可以像这样设置一个数组:

Object[] objects = {new Object()};

However if I have a method: 但是,如果我有一个方法:

public void setObject(Object[] objects) {

}

I cannot do the following: 我做不到以下事情:

setObject({new Object()});

Why is this? 为什么是这样? Why doesn't {new Object()} suffice as an argument but suffices to initialize an Object[] array? 为什么{new Object()}不足以作为参数,但足以初始化Object[]数组?

You can pass an anonymous array : 您可以传递一个匿名数组:

setObject(new Object[] { new Object() });

Note that the syntax { new Object() } just works when initializing the array on its declaration. 请注意,语法{ new Object() }在其声明初始化数组时才起作用。 For example: 例如:

Object[] arr = { new Object() };

This doesn't work after declaring the array: 声明数组后,这不起作用:

Object[] arr;
//uncomment below line and you'll get a compiler error
//arr = { new Object() };
arr = new Object[] { new Object() };

Because you haven't typed the Array. 因为您尚未键入数组。 It could be objects, integers, whatever. 它可以是对象,整数,等等。

The following should work: 以下应该有效:

setObject(new Object[]{new Object()});

适当的回调是:

setObject(new Object[]{new Object()});

Every Java array has a component type. 每个Java数组都有一个组件类型。 When used in an initializer, the compiler infers that the type of the new array (the right-hand side) is the same as the declared type (the left-hand side). 在初始化程序中使用时,编译器会推断新数组的类型(右侧)与声明的类型(左侧)相同。

When the declaration is missing, the compiler doesn't know what the component type of the array should be. 缺少声明时,编译器不知道数组的组件类型应该是什么。 You must be explicit, using the expression setObject(new Object[] { new Object() }) 你必须是显式的,使用表达式setObject(new Object[] { new Object() })

One might wonder why the compiler doesn't infer the type from the declared type of the method parameter, like it does when initializing a variable. 有人可能想知道为什么编译器不会从声明的方法参数类型推断出类型,就像初始化变量时一样。 But, the compiler resolves the method to call based on the parameter types; 但是,编译器根据参数类型解析调用方法; if you don't know the method you are calling, you can't infer anything from its parameter types. 如果您不知道要调用的方法,则无法从其参数类型中推断出任何内容。 There's no circularity when initializing a variable. 初始化变量时没有循环性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM