首页 > 解决方案 > 通过 ArrayList 从特定类访问变量

问题描述

我有一个名为的类Questions,它有两个子类multipleChoiceFillInBlank. 这两个子类每个都有唯一的实例变量。

现在假设我有一个ArrayList <Questions> questionswhich 存储两种类型的问题(multipleChoiceFillInBlank)。

我的问题是:当我遍历问题 ArrayList 时,如何从multipleChoice类和FillInBlank类中访问特定的实例变量?我遇到了麻烦,因为数组列表的类型是类型问题。

标签: javaarraylist

解决方案


正如评论中提到的,instanceof应该用来识别哪个子类是当前元素,然后这个元素应该被强制转换为这个子类:

for (Questions question : questions) {
    if (question instanceof MultipleChoice) {
        doSomething((MultipleChoice) question);
    } else if (question instanceof FillInBlank) {
        doSomething((FillInBlank) question);
    } else {
        System.out.println("Unexpected class: " + question.getClass());
    }
}

// ...
private void doSomething(MultipleChoice mc) {
    // do something
    System.out.println(mc.getChoice());
}

private void doSomething(FillInBlank fib) {
    // do something
    System.out.println(fib.getFilledAnswer());
}

推荐阅读