Why does a type conversion not work in Java
我想知道为什么这种转换不起作用:
1 | ArrayList<Song> arrayList =new ArrayList<MediaItem>(); |
我可能需要补充一下这首歌扩展了MediaItem。我认为这种转换应该有效,因为Song能够存储MediaItem中的所有信息。所以没有信息丢失。有人给我解释吗?
Does anyone have an explanation for me?
如果是,那么你可以有效的配置,把安subclass of another instance of
你
generictypes.faq101 about this在读更多P></
An instantiation of a generic type where all type arguments are concrete types rather than wildcards.
Examples of concrete parameterized types areList ,Map , but notList extends Number> orMap .
arrays在Java泛型的问题-什么是对arrays在Java泛型?P></
Generic collections are not covariant. An instantiation of a parameterized type for a supertype is not considered a supertype of an instantiation of the same parameterized type for a subtype. That is, a
LinkedList is not a supertype ofLinkedList and consequently aLinkedList cannot be used where aLinkedList is expected; there is no assignment compatibility between those two instantiations of the same parameterized type, etc.Here is an example that illustrates the difference:
LinkedList
这是你可以erasing parametrized压铸型模式:P></
1 | ArrayList<Song> arrayList = (ArrayList<Song>) (ArrayList<?>) new ArrayList<MediaItem>(); |
这是因为我没有在Java types GENERIC/逆协方差。如果你能给我一个茶样配置,能给我好的:to thisP></
1 2 3 4 5 6 7 8 9 | ArrayList<MediaItem> mediaItems = new ArrayList<MediaItem>(); // Legal ArrayList<Song> songs = mediaItems; // Illegal; let's imagine it's legal for a moment // Note that songs and mediaItems are the same list songs.add(new Song()); // This is perfectly fine Song firstSong = songs.get(0); // That's OK - it's a Song mediaItems.add(new Video()); // This is perfectly fine, too // However, the addition above also modifies songs: remember, it's the same list. // Now let's get the last object from songs Song lastSong = songs.get(1); // Wait, that's not a Song, it's a Video!!! |
Java does not this to要发生。因此,它prohibits assignments types of Generic基于subclasses types to the Generic基于对应的类。P></
这不会工作,因为在不covariant Java泛型。意思是,
这是contradictory。一个在线的手,