检查数组列表中的项目是否是在另一个 class 中创建的对象的实例

check if an item in an array list is an instanceof an object created in another class

我正在使用 foreach 循环遍历对象数组列表,这些对象都是在同一超级class的不同子class中创建的,然后是带有 instanceof 布尔表达式的语句检查每个循环现在属于哪个 subclass 特定项目,但我认为我没有使用正确实例的布尔表达式,因为在调试我的代码时,所有 if 语句都被跳过.

for (Appointment item: AppointmentBook.apps){


         if (item instanceof Onetime){
             boolean checkOnce = ((Onetime) item).occursOn(month, day, year);

             if (checkOnce == true){
                 appointmentsToday++;
                 appsToday.add(item);

             }//check once true 

             else appointmentsToday = 0;

         }//if onetime

Appointment 是 Onetime 的超class。 AppointmentBook 约会数组列表所在的class。 occursOn 是 Onetime class

中的一个方法

您应该始终避免这样的代码:

if (item instanceof TypeA) {
    ...
} else
if (item instanceof TypeB) {
    ...
} else ...

使用多态性,否则你会遭受高 coupling.

您使用“instanceof”的布尔表达式是正确的。我怀疑您用来从 AppointmentBook class 填充应用程序静态字段的方法是问题的根源。如果调试显示每个 if 语句都被跳过,那么这是唯一合乎逻辑的解释。我尝试重现一些与您的代码类似的代码以对其进行测试,它运行良好。

这是我做的

先预约class:

public class Appointment {

}

第二个约会簿class

import java.util.ArrayList;
import java.util.List;

public class AppointmentBook {

    public static List<Appointment> apps = new ArrayList<Appointment>();

    public AppointmentBook addAppointment(Appointment app) {
        apps.add(app);
        return this;
    }

}

第三个扩展 Appointment 的 OneTime class(因为你说 Appointment 是 OneTime 的超级class)

public class OneTime extends Appointment {

    public boolean occursOn(int month, int day, int year)  {
        if (day >= 15) {
            return true;
        } else {
            return false;
        }
    }
}

如您所见,我正在使用一个简单的测试用例来 return 来自 occursOn 方法的布尔结果(仅用于测试目的)

然后我创建了以下测试 class。我用四个 Appointment 实例填充 AppointmentBook 应用程序,其中两个是“instanceof”OneTime

public class AppointmentTest {

    static int year = 2015;
    static int month = 3;
    static int day = 15;

    public static void main(String[] args) {

        AppointmentBook book = new AppointmentBook();
        book.addAppointment(new Appointment())
        .addAppointment(new OneTime())
        .addAppointment(new Appointment())
        .addAppointment(new OneTime());

        for (Appointment item: AppointmentBook.apps) {

            if (item instanceof OneTime) {
                boolean checkOnce = ((OneTime)item).occursOn(month, day,    year);

                if (checkOnce == true) {
                    System.out.println("We have a checked OneTime     instance...");
                } else {
                    System.out.println("We have an unchecked OneTime     instance...");
                }
            } else {
                System.out.println("Not a OneTime instance...");
            }           
        }       
    }
}

得到的结果如下图所示:证明你的instanceof表达式是正确的,问题很可能是apps字段填写方法的问题