为什么类型转换在 Java 中不起作用 [英] Why does a type conversion not work in Java

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

问题描述

我想知道为什么这种转换不起作用:

I`m wondering why this conversion is not working:

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

我可能需要补充一点,Song 扩展了 MediaItem.我认为这种转换应该有效,因为 Song 能够存储 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天全站免登陆