casting Object[] to a reference type array in java

半腔热情 提交于 2021-02-05 04:50:17

问题


In implementation of a generic stack ,the following idiom is used and works without any problem

public class GenericStack<Item> {
    private int N;
    private Item[] data;    

    public GenericStack(int sz) {
        super();
        data = (Item[]) new Object[sz];

    }
        ...
}

However when I try the following ,it causes a ClassCastException

String[] stra = (String[]) new Object[4];

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

How do you explain this?


回答1:


Casting a new Object[4] to a String[] doesn't work because an Object[] isn't a String[], just like an Object isn't a String.

The first example works because of type erasure. At runtime, the type parameterItem has been erased to Object. However it would similarly fail if you tried to assign the array to a reifiable type, for example if data wasn't private:

String[] strings = new GenericStack<String>(42).data;

This would similarly throw a ClassCastException, because what is actually an Object[] would be cast to String[].




回答2:


Because of generics type erasure Item array becomes Object array effectivelly. Therefore type matches. But when you do it with concrete type String it does not. No type erasure is applied and it fails.




回答3:


I think if a Object class reference is pointing to any child class object like String class or any other class then only we can cast the object class reference to that particular class (which object we have created and assigned to Object class ref) and assign a reference to it. and if we create a direct object of Object class (as you have mentioned) will not work.

Example:

Object[] obj = new String[4];
String[] stra = (String[]) obj;

above code will not generate any ClassCastException.

Hope this helps




回答4:


I think this is the best answer to this question:

"A String[] is not an Object[], which is a little counter-intuitive. You're encountering the "Banana is-a fruit" but a "List Of Bananas is-not-a List Of Fruit" scenario."

Ref: https://stackoverflow.com/a/1018774/847818

From the same question, how to cast:

String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);

or

String[] stringArray = Arrays.asList(objectArray).toArray(new String[objectArray.length]);


来源:https://stackoverflow.com/questions/17108525/casting-object-to-a-reference-type-array-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!