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