private ArrayList<Doctor> doctors = new ArrayList<Doctor>();
doctors.add(new Doctor());
doctors.add(new Doctor());
doctors.add(new Doctor());
doctors.add(new Surgeon());
doctors.add(new Surgeon());
doctors.add(new Surgeon());
for (Doctor doctor: doctors) {
if (doctor.getAssignedPatient() != null) {
if (doctor.aDayPasses()) {
System.out.println("A " + convertSpecialism(doctor.getSpecialism()) + " treated their patient.");
shortBreak();
}
} else {
break;
}
}
工作正常,但是当我尝试这样做时:
for (Surgeon doctor: doctors) {
if (doctor.getAssignedPatient() != null) {
if (doctor.aDayPasses()) {
System.out.println("A " + convertSpecialism(doctor.getSpecialism()) + " treated their patient.");
shortBreak();
}
} else {
break;
}
}
有一个语法错误,我该如何循环遍历添加到type Doctor ArrayList中的外科医生。
假设外科医生扩大医生范围。
最佳答案
用两个词来说:你不能。因为ArrayList包含Doctor,并且您不能将该列表作为Surgeons列表进行迭代,因为Java不支持隐式向下转换。这与在不明确转换的情况下将Doctor分配给Surgeon相同。
因此,如果您想获得Surgeon,则应将其显式转换为Surgeon,如下所示:
for(Doctor d :doctors){
if (d instanceof Surgeon){
Surgeon s = (Surgeon) d;
...
}
}
但这是非常糟糕的做法,您不应该这样做。