1

I have a class like ChildData1 which extends from Data. How can I convert a List<List<ChildData1>> to a List<List<Data>> ?

2
  • I saw that question earlier and we cannot apply the same solution here. Though similar, they are not same. Commented 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. Commented Mar 25, 2014 at 6:14

4 Answers 4

0

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; 
Sign up to request clarification or add additional context in comments.

1 Comment

Earlier i tried with List<List<? extends Data>>. Thanks Oleg.
0

Traverse the elements of list and TYPECAST it.

Comments

0

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

-1

If Data is a parent no need to explicitly typecast it.

List<List<Data>>> data = somemethod(); List<List<ChildData>>> somemethod(){}; 

3 Comments

Type mismatch: cannot convert from List<List<ChildData>> to List<List<Data>>
childdata inherits the properties of parent data. It should
no, it shouldn't. that type system would be unsound, just like array covariant subtyping is unsound.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.