• Post Reply Bookmark Topic Watch Topic
  • New Topic

Defining List of ArrayList (Nested List) in Java  RSS feed

 
Alps Sharma
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a doubt when i try to declare a ArrayList containing List in following way , it works fine



But when i try to change the above declaration like



Compiler gives error.

My question is why compiler gives error in 3rd declaration.
There shouldn't be any problem while casting from nested ArrayList to nested List?
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you define something as List<List> then it would be legal to add a LinkedList (for example) to it.
Would you want a LinkedList added to your ArrayList<ArrayList> ?
 
Alps Sharma
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes I can use LinkedList too but my question is why compiler not allowing to use following syntax i.e nested Arraylist can't be type casted to nested List

List<List> list1 = new ArrayList<ArrayList>();
 
mike karl
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This has everything to do with generics i would recommend reading about it on the java site. -> Generics
But everything inside <HERE> is the type you will be using so you cannot say that you will use 2 types in your case a "list" and "arraylist" just like you wouldnt do this
int temp = new String();
although before you classify the type you can use inheritance since ArrayList inherits from List it is ok to do
List<Integer> temp = new ArrayList<Integer>(); but not ok to do this ArrayList<Integer> temp = new List<Integer>();
since List does not inherit from ArrayList
 
Chan Ag
Rancher
Posts: 1090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I thought you might want to refer to this
page?
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alps Sharma wrote:Yes I can use LinkedList too but my question is why compiler not allowing to use following syntax i.e nested Arraylist can't be type casted to nested List

List<List> list1 = new ArrayList<ArrayList>();

That isn't what I was saying.
You have a conflict.
The declarationdefines a variable that can point to a List that can hold any type of List, sowould be perfectly valid code.
But you have set list1 to point to a List that can only hold ArrayLists, so if the compiler allowed that, the code above where you add a LinkedList to your List would violate the type safety that generics is supposed to enforce.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!