关于泛型:为什么类型转换在Java中不起作用

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 Song(unrelated to completely into the list MediaItem)。因此,这是不允许的。在其他的话,不是covariant Java泛型。P></


ArrayLists have different parameterized型具体。P></

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 are List, Map, but not List or Map.

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 of LinkedList and consequently a LinkedList cannot be used where a LinkedList 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 objLst = new LinkedList(); // compile-time error

这是你可以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泛型。意思是,ListList全unrelated两类型,即使是SongMediaType相关。P></


这是contradictory。一个在线的手,Songs is of an declared ArrayList类和对象,我Songs of from there can be Song存储源。不管一个人多,new ArrayList()is an creating ArrayList of the meaning that other衍生型,对象从源directly Song我不能存储。差分irreconcilable is the between the types。P></