Java object class MYSTERY

When porting a game, I come to the description below

Object o = new Object[]{"A","B"};

This is really weird!

But when I try to do the same with "String" then the compiler will tell me the msg error

String s = new String [] {"A", "B", "C"}; Error: type mismatch: cannot convert from String [] to String

Could you tell us about the Mystery?

+4
source share
5 answers

You have a trivial error in your code. The fact that each class extends Object makes it difficult to find an error.

Since each class (including arrays) extends Object, conversion from A[]to is possible Object.

int i = new int[], , int[] i.

. Object a = new Object[] - , .

+5

Java Object. ,

Object o = new Object[]{"A","B"};

Object o = new String[]{"A","B"};// But array of String not a String 

Object o = new int[]{1,2};// But array of int not an int
+3

"" . "" ints int.    int , .

    Object[] obj = new Object[5];// works fine
+2

. , .

Object O = new Object[]{"S","A"};
  • , .
  • " " .
+1

Object[] AND a Object, :

Object[] o = new Object[]{"A","B"};
Object o = new Object[]{"A","B"};

However, a is String[] not a String(and vice versa) and int[] not a int(and vice versa).
Indeed, you must mix primitives with objects in this latter case.

0
source

Source: https://habr.com/ru/post/1535892/


All Articles