wood burning stoves 2.0*
The moose likes Java in General and the fly likes Polymorphic collection behavior Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Polymorphic collection behavior" Watch "Polymorphic collection behavior" New topic

Polymorphic collection behavior

Gerard Charles

Joined: Jan 21, 2010
Posts: 11
It's my understanding that, class A and class B extends A, a Collection<A> can not be (directly) assigned to from Collection<B>?

fails. However, I can get it to work if I put the cast inside a generic function:

updated test function works fine:

Is there a way to perform the cast without using a separate function? (And any explanation of why it works inside function but not directly would be cool, too.)
Ireneusz Kordal
Ranch Hand

Joined: Jun 21, 2008
Posts: 423
Gerard Charles wrote:
Is there a way to perform the cast without using a separate function?

Just cast to untyped collection:

Gerard Charles

Joined: Jan 21, 2010
Posts: 11
Oh, of course. "Collection" is okay but "Collection<A>" isn't. (I hate Java "generics").

Martin Vajsar

Joined: Aug 22, 2010
Posts: 3606

Here is explained the reason why Collection<B> cannot be assigned to Collection<A>: http://download.oracle.com/javase/tutorial/extra/generics/subtype.html. Another article has more on differences between arrays of related types and collections: http://www.ibm.com/developerworks/java/library/j-jtp01255.html

Maybe you could use generic wildcards to resolve your problem without the need for type-unsafe cast?
Gerard Charles

Joined: Jan 21, 2010
Posts: 11
Yes, using, Collection<? extends A> seems to work.
Matthew Brown

Joined: Apr 06, 2010
Posts: 4344

Basically, casting from Collection<B> to Collection<A> isn't safe. If it was allowed, it would give you a way of addings things other than B to a Collection<B>. Which defeats the whole object of generics.

Your generic method is effectively tricking the compiler. The compiler doesn't know what T and U are going to be. They could even be the same. So it will allow it, but it will generate warnings that you've had to suppress.

Then, because generic information doesn't exist at run time, the cast has no effect when it's running.

The bottom line is...if you're having to do this, there's almost certainly a better way! (Using wildcards might be it, depending on what you're actually trying to do).
I agree. Here's the link: http://aspose.com/file-tools
subject: Polymorphic collection behavior
Similar Threads
Doubt in K & B self test
Question on multi dimensional array
reference variable
Array declaration and initialization
very simple JAMon program giving error...