java - 如何检查 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:00
以30 分钟为间隔,毫秒或类似的东西没有问题。
到目前为止我做了什么:
我创建了以下方法,像这样遍历约会显示列表:
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 中。
我希望任何有经验的编码员都可以帮助我弄清楚我在这里做错了什么?先感谢您!
解决方案
对于对象,==
测试它们是否是同一个对象。假设它已经设置好,.equals()
测试它们是否具有相同的值。有关设置 .equals 的良好讨论,请参阅覆盖 equals 的很好的概述,包括此问题的可视化
这就是为什么您需要app.getStart().equals(ldt)
比较日期值,以查看两个对象是否代表相同的日期。app.getStart() == ldt
正在检查它们是否是同一个对象,这不是你想要的。
推荐阅读
- python - 如何在熊猫中将数组列读取为数组而不是字符串
- bash - 在命令链中的条件下退出中间命令
- java - SFTP 中每个文件的线程
- javascript - 无法使用打字稿向对象文字添加新属性
- javascript - 如何在另一个模块中使用一个模块并以角度 8 进行路由?
- amazon-web-services - DynamoDB Marshal 和 unmarshal golang time.Time as millis since epoch
- javascript - webview.executeJavascript 不是函数
- r - 在另一列的帮助下进行时间比较
- vb.net - 使用来自 Textbox 的 CEFSHARP 将文本输入网站
- google-maps - 如何向谷歌地图添加自定义路径并将其与方向 api 一起使用?