简体   繁体   中英

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 :

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.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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