[英]Assign literal array to object variable
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).
在Java编程语言中,数组是对象(§4.3.1),是动态创建的,可以分配给Object类型的变量(§4.3.2)。 All methods of class Object may be invoked on an array.
可以在数组上调用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, ie why is not it valid? 问题:我在第一个代码示例中缺少什么,即为什么它不是有效的?
PS: I'm almost sure that somebody already asked this question, because it seems so basic. PS:我几乎肯定有人已经问过这个问题了,因为它看起来很基本。 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:
虽然他们的头衔似乎很有希望,但他们都处理其他类型的问题,或者没有包含我的问题的答案:
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 . 数组初始值设定项只能显示为数组的初始值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.