从父类列表中提取子类元素 [英] Extract subclass elements from List of parent class

查看:70
本文介绍了从父类列表中提取子类元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I currently have a list like so:

List<Parent> parentList = new Arraylist<>;
//Code inserts elements of subclassA and subclass B into parentList above

现在,我想从parentList中提取属于子类A的元素.我想执行以下操作,但没有错误:

now I want to extract the elements from parentList who are of type subclass A. I want to do the following but without errors:

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

我不确定该怎么做.我不断收到错误,我将错误的对象类型/类添加到列表中,我理解为什么,但是我不知道如何更改代码以使其正常工作.

I am not sure how I can do this. I keep getting errors that I am adding what could be the wrong object type/class to the list and I understand why but I don't know how to change the code to make it work.

错误(我将类重命名为与上面使用的类匹配):

The error (I've renamed the classes to match the ones used above):

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)

推荐答案

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

There is a keyword in java called instanceof which compares an instantiated object against a class definition to see if that object is of that specific class type.

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

In your example you can use the instanceof keyword in your loop, then cast the parent object to a subclass and add it to your list.

for(Parent parent : parentList)
{
    if(parent instanceof SubclassA)
    {
        SubclassA subclass = (SubclassA)parent;
        extractMe.add(subclass);
    }
}

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

The casting of parent to subclass (SubclassA)parent is needed because even though you may have already checked that parent is of type SubclassA the compiler still does not know and as such you have to explicitly tell the compiler to cast the parent object to a SubclassA.

另外请注意, instanceof 关键字是Java中的内置二进制运算符,它将根据您随后指定的类检查父级.如果您可以将 parent 强制转换为 SubclassA ,那么 SubclassA的父实例为true.请参见 Oracle文档示例:

In addition note that the instanceof keyword is a built in binary operator in java which will check parent against the class you specify afterwards. parent instanceof SubclassA will only be true if you can cast parent to SubclassA. See the Oracle Docs Example:

类型比较运算符instanceof

The Type Comparison Operator instanceof

instanceof运算符将对象与指定类型进行比较.你可以用它来测试一个对象是否是一个类的实例,一个实例子类的实例,或实现特定实例的类的实例界面.

The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

以下程序InstanceofDemo定义了一个父类(名为父级),一个简单接口(名为MyInterface)和一个子类(名为子级)继承自父级并实现界面.

The following program, InstanceofDemo, defines a parent class (named Parent), a simple interface (named MyInterface), and a child class (named Child) that inherits from the parent and implements the interface.

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 {}

输出:

obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true

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

When using the instanceof operator, keep in mind that null is not an instance of anything.

这篇关于从父类列表中提取子类元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆