Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

January 18, 2010

Generics Reloaded

Generic collections give you the same benefits of type safety that you've always had with arrays, but there are some crucial differences that can bite you if you aren't prepared. Most of these have to do with polymorphism.

You've already seen that polymorphism applies to the "base" type of the collection:

List myList = new ArrayList();

In other words, we were able to assign an ArrayList to a List reference, because List is a supertype of ArrayList. Nothing special there—this polymorphic assignment works the way it always works in Java, regardless of the generic typing.

But what about this?

class Parent { }
class Child extends Parent { }
List myList = new ArrayList();

Think about it for a minute.
Keep thinking…

No, it doesn't work. There's a very simple rule here—the type of the variable declaration must match the type you pass to the actual object type. If you declare List foo then whatever you assign to the foo reference MUST be of the generic type . Not a subtype of . Not a supertype of .Just .

These are wrong:

List< Object > myList = new ArrayList(); // NO!
List numbers = new ArrayList(); // NO!
// remember that Integer is a subtype of Number

But these are fine:

List myList = new ArrayList(); // yes
List myList = new ArrayList(); // yes

No comments: