Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is casting from List<A> to List<B> not recommended?

Tags:

java

list

casting

I learned that if I have two classes:

public class A {}
public class B extends A {}

I can cast from a List<A> to List<B> by doing this:

List<B> list = (List<B>)(List<?>) collectionOfListA;

This would generate a warning, but it works. However, I read that this is not recommended. Is it true in that case?

If I know it's returning me a List<B>, why making this cast is such a bad practice?

Please note that I want to know why, in this case, this is a bad practice, not why there is a warning. And "it's a bad practice because it generates a warning" is not a good answer.

like image 397
Roberto Avatar asked Jan 15 '13 12:01

Roberto


1 Answers

An apple is a fruit, but a list of apples is-not a list of fruit.

If it was, you could put a banana in a list of apples

like image 185
Brian Agnew Avatar answered Oct 06 '22 01:10

Brian Agnew