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

More on Generics

look at the following statements and figure out which will compile:


1) List list = new ArrayList<dog>();
2) List aList = new ArrayList<dog>();
3) List foo = new ArrayList();
4) List cList = new ArrayList<integer>();
5) List bList = new ArrayList<animal>();
6) List dList = new ArrayList<dog>();

The correct answers (the statements that compile) are 1, 2, and 5. The three that won't compile are

Statement: List foo = new ArrayList();

Problem: you cannot use wildcard notation in the object creation. So the new ArrayList() will not compile.

Statement: List cList = new ArrayList();

Problem: You cannot assign an Integer list to a reference that takes only a Dog (including any subtypes of Dog, of course).

Statement: List dList = new ArrayList();

Problem: You cannot assign a Dog to . The Dog is too "low" in the class hierarchy. Only or < Object > would have been legal.

No comments: