首页 > 解决方案 > 如何检查 ObservableArray 中是否已存在具有重复 LocalDateTime 属性的对象?

问题描述

我写了一个方法 addAppointmentSaveButtonClicked 创建一个像这样的对象:

        Appointment newAppointment = new Appointment(appointmentId, chosenCustomerId, appointmentType, startDateTime, endDateTime, customerName);

然后它将该对象添加到 observableArrayList 中,如下所示:

        MainScreenController.appointmentDisplayList.add(newAppointment);

现在,当我想创建一个新的约会或编辑现有的约会时,我想检查约会显示列表数组中是否已经有一个具有相同开始时间的约会。

StartDateTime 是从组合框菜单中选择的 LocalDateTime 变量,它的格式始终如下:2020-02-15 10:30:0030 分钟为间隔,毫秒或类似的东西没有问题。

到目前为止我做了什么:

我创建了以下方法,像这样遍历约会显示列表:

    public static boolean existingAppointment(LocalDateTime ldt) {
    for (Appointment app : appointmentDisplayList) {
        if (app.getStart() == ldt) {
            System.out.println("True");
            return true;
        }
    }
    System.out.println("False");
    return false;
}

然后,每当单击保存按钮时,我都会在IF 代码块中放入对象创建代码,如下所示:

if(!existingAppointment(startDateTime)) {
        AppointmentMethods.addAppointment(appointmentType, chosenCustomerId, utcStartTime, utcEndTime);
        appointmentId = AppointmentMethods.getAppointment(chosenCustomerId, utcStartTime).getAppointmentId();

        Appointment newAppointment = new Appointment(appointmentId, chosenCustomerId, appointmentType, startDateTime, endDateTime, customerName);
        MainScreenController.appointmentDisplayList.add(newAppointment);}

现在我的代码遇到的问题是,我为我的新任命者选择的每一个时间和日期,这个 if 块总是错误的,并且重复的任命被添加到我的 ArrayList 中。

我希望任何有经验的编码员都可以帮助我弄清楚我在这里做错了什么?先感谢您!

标签: javajavafx

解决方案


对于对象,==测试它们是否是同一个对象。假设它已经设置好,.equals()测试它们是否具有相同的值。有关设置 .equals 的良好讨论,请参阅覆盖 equals 的很好的概述,包括此问题的可视化

这就是为什么您需要app.getStart().equals(ldt)比较日期值,以查看两个对象是否代表相同的日期。app.getStart() == ldt正在检查它们是否是同一个对象,这不是你想要的。


推荐阅读