• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

KB question pg 611

 
Dinesh Tahiliani
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public static void main(String a[])
{
// insert code
for(int i =0; i<=10;i++){
List<Integer> l = new Arraylist<Integer> ();
for(int j =0; j<=10;j++)
row.add(i*j);
table.add(row);
}

for(List<Integer> row :table)
System.out.println(row);
}

options ar e:
1.List<List<Integer>> table = new ArrayList<List<Integer>>();
2. List<List<Integer>> table = new ArrayList<Arraylist<Integer>>();
3. List<List,Integer>> table = new ArrayList<List,Integer>();
4. List<List<Integer>> table = new List<List,Integer>();

answer is : 1
I am not getting the answer. Please help me out to understnad.
 
Krishnamoorthy Vuyala Muralidharan
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Dinesh

I would request you to type the code exactly(I mean without errors) as it is written in K&B book(in this case). In this way, you save the time of those who would like to help you (us in general).

The code in the K&B book is as follows:

public static void main(String[] args) {
// Insert declaration here

for (int i = 0; i <=10; i++) {
List<Integer> row = new ArrayList<Integer>();
for (int j = 0; j <=10; j++)
row.add(i*j);
table.add(row);
}
for (List<Integer> row : table) {
System.out.println(row);
}
}


A. List<List<Integer>> table = new List<List<Integer>>();
B. List<List<Integer>> table = new ArrayList<List<Integer>>();
C. List<List<Integer>> table = new ArrayList<ArrayList<Integer>>();
D. List<List,Integer> table = new List<List,Integer>();
E. List<List,Integer> table = new ArrayList<List,Integer>();
F. List<List,Integer> table = new ArrayList<ArrayList,Integer>();
G. None above

Explanation about answers:

A is incorrect - because you cannot instantiate an interface. List is an interface
B is correct - What the above code is doing is populating integers into a List and then finally placing this List into an another List
In generics, we dont say just List but we parameterize it, that is List<Integer> in this example. so it is clear that it is List<List<Integer>>.
An another important point is that the polymorphisim is not possible for generics parameters. That is, to make it simple:

what you see in the lefthandside(declaration of a reference variable) <List<Integer>> must match to the right-hand side of the assignment.
So,

List<List<Integer>> table = new ArrayList<List<Integer>>() is correct but 'new ArrayList<ArrayList<Integer>>()' is not possible. Hope this is clear.

C. Is incorrect as per the explanation above.
D. Is incorrect as List contains only one object not key and value like HashMap or HashSet and so on..
E. Is incorrect for the same reason as D.
F. Is incorrect as the same reason as D.

Best Regards
Kris
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic