If an array of Object is an Object, why is an array of String not a String

后端 未结 6 1401
心在旅途
心在旅途 2021-02-15 12:06

Object class is super class to every class in Java. So every class should inherent the properties or behavior of Object class.

Then we can declare array of objects as sh

6条回答
  •  南旧
    南旧 (楼主)
    2021-02-15 12:45

    Object c = new Object[] {1,2,"22" };
    

    is valid due to the fact that an array of Objects is still an Object. You could specify that c is an array of Objects at declaration level too, like this:

    Object[] c = new Object[] {1,2,"22" };
    

    However,

    String s = new String[]{"s","s"};
    

    is not valid, since an array of Strings is not a String. You need either to convert your array into a String, like this:

    String s = String.join(",", new String[]{"s","s"});
    

    or to store it as an array, like this:

    String[] s = new String[]{"s","s"};
    

提交回复
热议问题