将文字数组指定给对象变量

时间:2022-01-20 01:15:42

Consider the following code:

请考虑以下代码:

Object obj = {};

This results in the following error:

这会导致以下错误:

Type mismatch: cannot convert from Object[] to Object

However, according to the Java standard every Array is an Object:

但是,根据Java标准,每个Array都是一个Object:

In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.

在Java编程语言中,数组是对象(§4.3.1),是动态创建的,可以分配给Object类型的变量(§4.3.2)。可以在数组上调用Object类的所有方法。

Besides that, the following snippet compiles without any problems:

除此之外,以下代码段编译没有任何问题:

Object [] arr = {};
Object obj = arr;

Question: what am I missing in the first code sample, i.e. why is not it valid?

问题:我在第一个代码示例中缺少什么,即为什么它不是有效的?

P.S.: I'm almost sure that somebody already asked this question, because it seems so basic. However, I could not find any useful results neither here, nor in Google (maybe because square brackets are ignored in the search?). If there is a duplicate, which I missed, then please feel free to close my question. For the records, I checked the following questions. While their title seemed promising, they were all dealing with other kinds of issues, or did not contain the answer to my question:

P.S。:我几乎肯定有人已经问过这个问题,因为它看起来很基本。但是,我既没有在这里找到任何有用的结果,也没有在Google中找到任何有用的结果(可能是因为在搜索中忽略了方括号?)。如果有重复,我错过了,那么请随时关闭我的问题。为了记录,我检查了以下问题。虽然他们的头衔似乎很有希望,但他们都处理其他类型的问题,或者没有包含我的问题的答案:

1 个解决方案

#1


0  

In-line array initialization can only be used for array type declarations - it's part of the syntax of the language.

内联数组初始化只能用于数组类型声明 - 它是语言语法的一部分。

In java 8, this line

在java 8中,这一行

Object o = {};

does not give the compile error you report. Instead, it gives:

不会给出您报告的编译错误。相反,它给出:

Array initializer not allowed here

这里不允许使用数组初始化程序

Array initializers can only appear as the initial value of an array.

数组初始值设定项只能显示为数组的初始值。

#1


0  

In-line array initialization can only be used for array type declarations - it's part of the syntax of the language.

内联数组初始化只能用于数组类型声明 - 它是语言语法的一部分。

In java 8, this line

在java 8中,这一行

Object o = {};

does not give the compile error you report. Instead, it gives:

不会给出您报告的编译错误。相反,它给出:

Array initializer not allowed here

这里不允许使用数组初始化程序

Array initializers can only appear as the initial value of an array.

数组初始值设定项只能显示为数组的初始值。