Java – although the type is the same, I get the ClassCastException event Why?

I'm not very new to Java, although I've never really used sets before,

I have the following questions; But first, this is my code:

HashMap<Position[],String> save = io.getSave();

Position[][] saved_pos = (Position[][]) save.keySet().toArray();

Although Java throws ClassCastException in the second line, why? Obviously, save keySet(). The array returned by toarray() does contain position [] [] s, although unfortunately, toarray() in class set only returns an object [] array

So what can I do? I need to vote for this

Solution

The toArray () method does not actually know that it is called in a group of position [] s; It only knows that it is called on a group (this is because of how generics are implemented in Java; there is not much information available at runtime.) Therefore, it only returns a complete partition [] s object [], rather than a real partition [] (the difference is that object [] can contain any object - after the call, writing saved_pos [0] = new object() will be valid - while the real partition [] [] will cause arraystoreexception. If you try, set one of the elements to new object().)

Fortunately, a separate toArray (...) method can be used. You can tell it the type of array you want, as follows:

Position[][] saved_pos = save.keySet().toArray(new Position[0][]);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>