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

前端 未结 17 1282
面向向阳花
面向向阳花 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: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 result = .... 
    List data = new List();
    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.

提交回复
热议问题