Java – assign a text array to an object variable

Consider the following codes:

Object obj = {};

This results in the following errors:

Type mismatch: cannot convert from Object[] to Object

However, according to the Java standard, every array is an object:

In addition, the following code snippets have no problems compiling:

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

Question: what am I missing in the first code example, that is, why isn't it valid?

P. S.: I'm almost sure someone has asked this question because it looks basic However, I didn't find any useful results in Google (perhaps because I ignored square brackets?) If there is repetition and I miss it, please close my question at any time For the record, I checked the following questions Although their titles seem promising, they all deal with other types of questions or do not contain answers to my questions:

> Question 1 > Question 2 > Question 3 > Question 4 > Question 5 > Question 6

Solution

Inline array initialization can only be used for array type declarations - it is part of language syntax

In Java 8, this line

Object o = {};

The compilation errors you report will not be given Instead, it gives:

Array initializers can only be displayed as array initializers

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>