从父类的List中提取子类元素

jig*_*ard 1 java inheritance

我目前有一个这样的列表:

List<Parent> parentList = new Arraylist<>;
//Code inserts elements of subclassA and subclass B into parentList above
Run Code Online (Sandbox Code Playgroud)

现在我想从parentList中提取类型为子类A的元素.我想做以下但没有错误:

List<SubclassA> extractMe = new Arraylist<>;
for (Parent parent: parentList){
    if (parent.isSubclassA()){extractMe.add(parent);}
}
Run Code Online (Sandbox Code Playgroud)

我不知道怎么能这样做.我不断收到错误,我在列表中添加了错误的对象类型/类,我理解为什么,但我不知道如何更改代码以使其工作.

编辑:

错误(我重命名了类以匹配上面使用的类):

Error:(53, 20) java: no suitable method found for add(Parents.Parent)
        method java.util.Collection.add(Parents.SubclassA) is not applicable
          (argument mismatch; Parents.Parent cannot be converted to Parents.SubclassA)
        method java.util.List.add(Parents.SubclassA) is not applicable
          (argument mismatch; Parents.Parent cannot be converted to Parents.SubclassA)
Run Code Online (Sandbox Code Playgroud)

cha*_*cea 5

在java中有一个关键字,instanceof它将实例化对象与类定义进行比较,以查看该对象是否属于该特定类类型.

在您的示例中,您可以在循环中使用instanceof关键字,然后将父对象强制转换为子类并将其添加到列表中.

for(Parent parent : parentList)
{
    if(parent instanceof SubclassA)
    {
        SubclassA subclass = (SubclassA)parent;
        extractMe.add(subclass);
    }
}
Run Code Online (Sandbox Code Playgroud)

需要将父类转换为子类(SubclassA)parent,因为即使可能已经检查过编译器仍然不知道parent的类型,因此您必须明确告诉编译器将对象强制转换为. SubclassAparentSubclassA

另外请注意,instanceof关键字是java中的内置二进制运算符,它将根据您之后指定的类检查父级. parent instanceof SubclassA只能是真实的,如果你能投parentSubclassA.请参阅Oracle Docs示例:

类型比较运算符instanceof

instanceof运算符将对象与指定的类型进行比较.您可以使用它来测试对象是否是类的实例,子类的实例或实现特定接口的类的实例.

以下程序InstanceofDemo定义了一个父类(名为Parent),一个简单的接口(名为MyInterface),以及一个从父级继承并实现接口的子类(名为Child).

class InstanceofDemo {
    public static void main(String[] args) {

        Parent obj1 = new Parent();
        Parent obj2 = new Child();

        System.out.println("obj1 instanceof Parent: "
            + (obj1 instanceof Parent));
        System.out.println("obj1 instanceof Child: "
            + (obj1 instanceof Child));
        System.out.println("obj1 instanceof MyInterface: "
            + (obj1 instanceof MyInterface));
        System.out.println("obj2 instanceof Parent: "
            + (obj2 instanceof Parent));
        System.out.println("obj2 instanceof Child: "
            + (obj2 instanceof Child));
        System.out.println("obj2 instanceof MyInterface: "
            + (obj2 instanceof MyInterface));
    }
}

class Parent {}
class Child extends Parent implements MyInterface {}
interface MyInterface {}
Run Code Online (Sandbox Code Playgroud)

输出:

obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true
Run Code Online (Sandbox Code Playgroud)

使用instanceof运算符时,请记住null不是任何实例.