Casting Object [] to an array of reference type in java

The following idiom is used in the implementation of the common stack and works without problems

public class GenericStack<Item> { private int N; private Item[] data; public GenericStack(int sz) { super(); data = (Item[]) new Object[sz]; } ... } 

However, when I try to do the following, it throws 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?

+6
source share
4 answers

Sending new Object[4] to String[] does not work because Object[] not String[] , just as Object not String .

The first example works because of the type of erasure . At run time, a parameter of type Item was deleted to Object . However, this will also work if you tried to assign an array to the return type, for example, if data not private :

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

This would also throw a ClassCastException , because in fact Object[] would be discarded on String[] .

+3
source

Due to the erasure of generics styles. An array element becomes an array of objects massive. So enter matches. But when you do this with a specific String type, it is not. Type erasure does not apply and it does not work.

+2
source

I think that if the reference of the Object class points to any object of the child class, such as the String class or any other class, then we can apply the object class reference to this particular class (which object we created and assigned to the Object ref class) and assign a reference to him. and if we create a direct object of class Object (as you already mentioned), this will not work.

Example:

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

the above code will not throw any ClassCastException.

Hope this helps

+1
source

I think this is the best answer to this question:

"The string [] is not an object [], which is a little contrary to intuition. You come across" Banana is a fruit, "but" The list of bananas is not a list of fruits, "scenario". Strike>

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

From the same question how to do:

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

or

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

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


All Articles