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

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

    You can use the selectInstances method in Eclipse Collections. This will involved creating a new collection however so will not be as efficient as the accepted solution which uses casting.

    List parent =
            Arrays.asList("1","2","3", new StringBuffer("4"));
    List strings =
            Lists.adapt(parent).selectInstancesOf(String.class);
    Assert.assertEquals(Arrays.asList("1","2","3"), strings);
    

    I included StringBuffer in the example to show that selectInstances not only downcasts the type, but will also filter if the collection contains mixed types.

    Note: I am a committer for Eclipse Collections.

提交回复
热议问题