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

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

    I think you are casting in the wrong direction though... if the method returns a list of TestA objects, then it really isn't safe to cast them to TestB.

    Basically you are asking the compiler to let you perform TestB operations on a type TestA that does not support them.

    0 讨论(0)
  • 2020-11-22 09:11

    Since this is a widely referenced question, and the current answers mainly explain why it does not work (or propose hacky, dangerous solutions that I would never ever like to see in production code), I think it is appropriate to add another answer, showing the pitfalls, and a possible solution.


    The reason why this does not work in general has already been pointed out in other answers: Whether or not the conversion is actually valid depends on the types of the objects that are contained in the original list. When there are objects in the list whose type is not of type TestB, but of a different subclass of TestA, then the cast is not valid.


    Of course, the casts may be valid. You sometimes have information about the types that is not available for the compiler. In these cases, it is possible to cast the lists, but in general, it is not recommended:

    One could either...

    • ... cast the whole list or
    • ... cast all elements of the list

    The implications of the first approach (which corresponds to the currently accepted answer) are subtle. It might seem to work properly at the first glance. But if there are wrong types in the input list, then a ClassCastException will be thrown, maybe at a completely different location in the code, and it may be hard to debug this and to find out where the wrong element slipped into the list. The worst problem is that someone might even add the invalid elements after the list has been casted, making debugging even more difficult.

    The problem of debugging these spurious ClassCastExceptions can be alleviated with the Collections#checkedCollection family of methods.


    Filtering the list based on the type

    A more type-safe way of converting from a List<Supertype> to a List<Subtype> is to actually filter the list, and create a new list that contains only elements that have certain type. There are some degrees of freedom for the implementation of such a method (e.g. regarding the treatment of null entries), but one possible implementation may look like this:

    /**
     * Filter the given list, and create a new list that only contains
     * the elements that are (subtypes) of the class c
     * 
     * @param listA The input list
     * @param c The class to filter for
     * @return The filtered list
     */
    private static <T> List<T> filter(List<?> listA, Class<T> c)
    {
        List<T> listB = new ArrayList<T>();
        for (Object a : listA)
        {
            if (c.isInstance(a))
            {
                listB.add(c.cast(a));
            }
        }
        return listB;
    }
    

    This method can be used in order to filter arbitrary lists (not only with a given Subtype-Supertype relationship regarding the type parameters), as in this example:

    // A list of type "List<Number>" that actually 
    // contains Integer, Double and Float values
    List<Number> mixedNumbers = 
        new ArrayList<Number>(Arrays.asList(12, 3.4, 5.6f, 78));
    
    // Filter the list, and create a list that contains
    // only the Integer values:
    List<Integer> integers = filter(mixedNumbers, Integer.class);
    
    System.out.println(integers); // Prints [12, 78]
    
    0 讨论(0)
  • 2020-11-22 09:12

    The only way I know is by copying:

    List<TestB> list = new ArrayList<TestB> (
        Arrays.asList (
            testAList.toArray(new TestB[0])
        )
    );
    
    0 讨论(0)
  • 2020-11-22 09:15

    When you cast an object reference you are just casting the type of the reference, not the type of the object. casting won't change the actual type of the object.

    Java doesn't have implicit rules for converting Object types. (Unlike primitives)

    Instead you need to provide how to convert one type to another and call it manually.

    public class TestA {}
    public class TestB extends TestA{ 
        TestB(TestA testA) {
            // build a TestB from a TestA
        }
    }
    
    List<TestA> result = .... 
    List<TestB> data = new List<TestB>();
    for(TestA testA : result) {
       data.add(new TestB(testA));
    }
    

    This is more verbose than in a language with direct support, but it works and you shouldn't need to do this very often.

    0 讨论(0)
  • 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 <TCastTo, TCastFrom extends TCastTo> List<TCastTo> convert(final List<TCastFrom> list)
        {
            return new AbstractList<TCastTo>() {
                @Override
                public TCastTo get(int i)
                {
                    return list.get(i);
                }
    
                @Override
                public int size()
                {
                    return list.size();
                }
            };
        }
    
        public static <TCastTo, TCastFrom> List<TCastTo> cast(final List<TCastFrom> list)
        {
            return new AbstractList<TCastTo>() {
                @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<TestA> listA, List<TestB> listB)
    {
        List<TestB> castedB = ListUtil.cast(listA); // all items are blindly casted
        List<TestB> convertedB = ListUtil.<TestB, TestA>convert(listA); // wrong cause TestA does not extend TestB
        List<TestA> convertedA = ListUtil.<TestA, TestB>convert(listB); // OK all items are safely casted
    }
    
    0 讨论(0)
提交回复
热议问题