How do you cast a List of supertypes to a List of subtypes?

前端 未结 17 1505
面向向阳花
面向向阳花 2020-11-22 08:43

For example, lets say you have two classes:

public class TestA {}
public class TestB extends TestA{}

I have a method that returns a L

17条回答
  •  孤独总比滥情好
    2020-11-22 09:04

    You cannot cast List to List as Steve Kuo mentions BUT you can dump the contents of List into List. Try the following:

    List result = new List();
    List data = new List();
    result.addAll(data);
    

    I've not tried this code so there are probably mistakes but the idea is that it should iterate through the data object adding the elements (TestB objects) into the List. I hope that works for you.

提交回复
热议问题