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

前端 未结 17 1518
面向向阳花
面向向阳花 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:08

    Quite strange that manually casting a list is still not provided by some tool box implementing something like:

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static  List cast(List list) {
        return (List) list;
    }
    

    Of course, this won't check items one by one, but that is precisely what we want to avoid here, if we well know that our implementation only provides the sub-type.

提交回复
热议问题