Java – why can a generic list be cast to its type parameter
•
Java
Why does the following code compile?
What's the meaning of this?
//Connection can be substituted by any interface List<Connection> list = null; Connection c = (Connection) list;
Solution
This is independent of the type parameter This also works:
List<String> list = null; Connection c = (Connection) list;
This is possible because list is an interface type The list reference may contain an object that implements the list interface and a connection (whether class or interface), so the conversion works
Therefore, since the actor can work, the compiler allows it It will only reject theoretically impossible casts, that is, involving specific types in a separate inheritance hierarchy:
JComponent c = null; ArrayList l = (ArrayList) c;
You can find the exact rules for which types of cast are legal when compiling Java language specification - this is about 30 lines of intensive language
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
二维码