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

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

    The best safe way is to implement an AbstractList and cast items in implementation. I created ListUtil helper class:

    public class ListUtil
    {
        public static  List convert(final List list)
        {
            return new AbstractList() {
                @Override
                public TCastTo get(int i)
                {
                    return list.get(i);
                }
    
                @Override
                public int size()
                {
                    return list.size();
                }
            };
        }
    
        public static  List cast(final List list)
        {
            return new AbstractList() {
                @Override
                public TCastTo get(int i)
                {
                    return (TCastTo)list.get(i);
                }
    
                @Override
                public int size()
                {
                    return list.size();
                }
            };
        }
    }
    

    You can use cast method to blindly cast objects in list and convert method for safe casting. Example:

    void test(List listA, List listB)
    {
        List castedB = ListUtil.cast(listA); // all items are blindly casted
        List convertedB = ListUtil.convert(listA); // wrong cause TestA does not extend TestB
        List convertedA = ListUtil.convert(listB); // OK all items are safely casted
    }
    

提交回复
热议问题