为什么一个类型的转换不是在Java中工作 [英] Why does a type conversion not work in Java

查看:111
本文介绍了为什么一个类型的转换不是在Java中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不知道为什么这种转换是不工作:

I`m wondering why this conversion is not working:

ArrayList<Song> arrayList =new ArrayList<MediaItem>();

我可能要补充一点,宋延伸MediaItem。
我想,这应该转换工作,因为宋有存储所有信息表MediaItem的能力。因此,没有信息丢失。
没有人有一个解释吗?

I may have to add that Song extends MediaItem. I think this conversion should work because Song has the ability to store all the information form MediaItem. So no information is lost. Does anyone have an explanation for me?

推荐答案

这是因为泛型类型在Java中没有的协方差/逆变。如果你可以做这样的分配,人们将能够做到这一点:

This is because generic types in Java have no covariance/contravariance. If you could do the assignment like that, one would be able to do this:

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不希望这种情况发生。因此,它基于子类基于相应的基类的泛型类型禁止泛型类型的任务。

Java does not want this to happen. Hence, it prohibits assignments of generic types based on subclasses to generic types based on the corresponding base classes.

这篇关于为什么一个类型的转换不是在Java中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆