I am trying to create a list of list of strings,
List<List<String>> string= new ArrayList<ArrayList<String>>();
and getting Type Mismatch error:cannot convert from ArrayList<ArrayList<String>> to List<List<String>>.
I know I can change
List<List<String>> to ArrayList<ArrayList<String>>
and it will work fine.
But I was just wondering why doesn’t it let it happen? Simple List<Object> can refer to ArrayList<Object> so what is different about this?
Because a
List<List<String>>would accept other lists of strings that were not array lists, which is not how you declared the type initially. For example, if you converted to aList<List<String>>, you would technically be allowed to add aLinkedList<String>to it! And that’s not anArrayList<String>. Allowing that cast would effectively break the generic type system.In other words, you could convert to
List<ArrayList<String>>. But notList<List<String>>.