将子类添加到数组列表然后进行高级

时间:2014-12-07 19:32:21

标签: java

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

有一个语法错误,我如何循环通过我已经添加到医生类型的ArrayList的外科医生。

假设外科医生延长医生。

3 个答案:

答案 0 :(得分:2)

用两个词说:你做不到。因为ArrayList包含Doctor,并且您不能将该列表作为外科医生列表进行迭代,因为Java不支持隐式向下转换。这与将医生分配给外科医生而不明确地向下转发相​​同。

因此,如果您想获得外科医生,您应该明确地将其转换为外科医生:

   for(Doctor d :doctors){
        if (d instanceof Surgeon){
            Surgeon s = (Surgeon) d;
            ...
        }
   } 

但这是非常糟糕的做法,你不应该这样做。

答案 1 :(得分:0)

您无法创建for-each循环(for (SubClass subClass : superClasses)),因为编译器无法确保只有SubClassSurgeon)类型的对象。

答案 2 :(得分:0)

你可以这样做:

for (Doctor doctor : doctors) {
    if (doctor instanceof Surgeon) {
        if (doctor.getAssignedPatient() != null) {
            if (doctor.aDayPasses()) {
                System.out.println("A "
                    + convertSpecialism(doctor.getSpecialism())
                    + " treated their patient.");
                shortBreak();
            }
        } else {
            break;
        }
    }
}