Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

S&B 1.5, Chapter 7, Question 2, answer C

 
David Wooddall-Gainey
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

which can be inserted

A.List<List<Integer>> table = new List<List<Integer>>();
B.List<List<Integer>> table = new List<ArrayList<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

Why is c wrong? Given explanation "the type argument <List<Integer>> must be the same on both sides of the assignment even though the constructor new ArrayList() on the right side is a subtype of the declared type List on the left side." Why does the type arg have to be the same?

Thanks
 
Nabila Mohammad
Ranch Hand
Posts: 664
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
C. List<List<Integer>> table = new ArrayList<ArrayList<Integer>>();


Genrics doesn't allow you to write subclasses like that - meaning
you can't write :
List<Animal> l=new ArrayList<Dog>();

it should be
List<Dog> l=new ArrayList<Dog>();
List<Animal> l=new ArrayList<Animal>();

Both the types should be the same.

You cant even write
List<Number> n=new ArrayList<Integer>();

Hope you got the picture....
 
Ankit Garg
Sheriff
Posts: 9529
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So does that mean only A is the correct answer right???
 
Manju Kavi
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes Nabila is right. But here none of the option is right. Option "A" and "B" are wrong because List is an interface and you cannot call constructor on it. "C" is wrong according to what Nabila said, which is correct.
 
Rekha Srinath
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If C was modified a little as
List<List<Integer>> table = new ArrayList<List<Integer>>();
it would have been correct.
 
David Wooddall-Gainey
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks and apologies to all. The correct answer is B which SHOULD read


(I am tying while riding on a bus to work!)

Nabila, do you mean since the left side of the assignment contains
List<List<Integer>> the base class is List while the generic class is List<Integer>. Base and Generic are terms from S&B Chap 7. If this is the case then, yes I understand you explanation. And thank you very much.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic