java - 通过 ArrayList 从特定类访问变量
问题描述
我有一个名为的类Questions
,它有两个子类multipleChoice
和FillInBlank
. 这两个子类每个都有唯一的实例变量。
现在假设我有一个ArrayList <Questions> questions
which 存储两种类型的问题(multipleChoice
和FillInBlank
)。
我的问题是:当我遍历问题 ArrayList 时,如何从multipleChoice
类和FillInBlank
类中访问特定的实例变量?我遇到了麻烦,因为数组列表的类型是类型问题。
解决方案
正如评论中提到的,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());
}
推荐阅读
- css - 内联样式属性的 CSS 选择器,同时排除属性值
- python - 如何在 Plotly Express 平行坐标图中格式化刻度?
- oracle - 使用 perl 运行 oracle 生产者
- python - 在 django 模板中迭代字典时卡住了
- swiftui - onTapGesture 会劫持事件吗?
- javascript - 在代码沙箱中使用 npm 包对 web worker 做出反应
- java - 无法使用作为映射值传递的 Java SQL 语句对象访问临时表
- ruby-on-rails - 如何修复“用户中的加载错误::RegistrationsController#create”
- alpine - 如何登录:“按照 firecracker custom rootfs using alpine 中的步骤进行操作后”
- ios - 在 iCloud Drive 中执行“NSMetadataQuery”时出错