Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a type conversion not work in Java [duplicate]

I`m wondering why this conversion is not working:

ArrayList<Song> arrayList =new ArrayList<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?

like image 987
Asker Avatar asked Aug 05 '26 11:08

Asker


2 Answers

Does anyone have an explanation for me?

If that assignment were valid, then you could put an instance of another subclass of Song (completely unrelated to MediaItem) into the list. Hence it's not allowed. In other words, Java generics are not covariant.

like image 194
arshajii Avatar answered Aug 07 '26 01:08

arshajii


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 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.

like image 21
Sergey Kalinichenko Avatar answered Aug 07 '26 00:08

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!