• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Devaka Cooray
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Saloon Keepers:
  • Tim Holloway
Bartenders:

SCJP5 Study Guide Q2. Page 611/622 -- Generics and Collections

 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear ranchers,

I have a query in the following question that I have customized a bit for testing purpose:

Given:-


Which statements could be inserted at // INSERT DECLARATION HERE to allow this code to compile and run? (Choose all that apply.)

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 of the above.

Correct Answer is B.

What if I modify option C a bit to make it look like the following ..and try to recompile and run. But it doesn't compile, why? What is wrong with the type declaration here?

List<ArrayList<Integer>> table = new ArrayList<ArrayList<Integer>>();

-------------
Ravinder
 
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
By saying, table.add(row), what you are actually inserting is a List of Integers. Here you cannot add an ArrayList of Integers because you cannot say that a super-class is same as a subclass.

So,

List<ArrayList<Integer>> table = new ArrayList<ArrayList<Integer>>();

will not work. It'll work if you explicitely cast it to an ArrayList.



regards,
vijay.
 
In the renaissance, how big were the dinosaurs? Did you have tiny ads?
Paul Wheaton's 16th Kickstarter: Gardening playing cards for gardeners and homesteaders
https://coderanch.com/t/889615/Paul-Wheaton-Kickstarter-Gardening-playing
reply
    Bookmark Topic Watch Topic
  • New Topic