I have a class like ChildData1 which extends from Data. How can I convert a List<List<ChildData1>> to a List<List<Data>> ?
- I saw that question earlier and we cannot apply the same solution here. Though similar, they are not same.Sakthi Priyan H– Sakthi Priyan H2014-03-25 06:10:49 +00:00Commented Mar 25, 2014 at 6:10
- The extra list doesn't make a difference here. The solution provided (along with the other answers) are still applicable.Nathan Merrill– Nathan Merrill2014-03-25 06:14:06 +00:00Commented Mar 25, 2014 at 6:14
Add a comment |
4 Answers
Under the rules of generics you can do the following assignment without the cast:
List<List<ChildData>> subClassList = ... List<? extends List<? extends Data>> superClassList = subClassList; 1 Comment
Sakthi Priyan H
Earlier i tried with List<List<? extends Data>>. Thanks Oleg.
Imagine if you could do this:
List<List<ChildData1>> foo = getListOfListOfChildData(); List<List<Data>> bar = foo; // there's your cast ChildData2 childData2 = getSomeOtherChildData(); bar.get(0).add(childData2); // now you've added ChildData2 for (ChildData1 childData1 : foo.get(0)) { // Whoops! Suddenly you've got a ChildData2 in your ChildData1. } These types are not naturally compatible, and not easily converted to one another without some kind of @SuppressWarnings.
Comments
If Data is a parent no need to explicitly typecast it.
List<List<Data>>> data = somemethod(); List<List<ChildData>>> somemethod(){}; 3 Comments
Sakthi Priyan H
Type mismatch: cannot convert from List<List<ChildData>> to List<List<Data>>
Shriram
childdata inherits the properties of parent data. It should
Judge Mental
no, it shouldn't. that type system would be unsound, just like array covariant subtyping is unsound.