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

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

    The problem is that your method does NOT return a list of TestA if it contains a TestB, so what if it was correctly typed? Then this cast:

    class TestA{};
    class TestB extends TestA{};
    List listA;
    List listB = (List) listA;
    

    works about as well as you could hope for (Eclipse warns you of an unchecked cast which is exactly what you are doing, so meh). So can you use this to solve your problem? Actually you can because of this:

    List badlist = null; // Actually contains TestBs, as specified
    List talist = badlist;  // Umm, works
    List tblist = (List)talist; // TADA!
    

    Exactly what you asked for, right? or to be really exact:

    List tblist = (List)(List) badlist;
    

    seems to compile just fine for me.

提交回复
热议问题