java - 检查对象是否已存在于 Java ArrayList 中

标签 java arraylist

<分区>

我想使用唯一 ID nhsNumber 检查患者对象是否已存在于 ArrayList 队列中。但是当我将一个我知道队列中已经存在的患者添加到队列中时,以下代码不会检测到它。知道这是为什么吗?

public boolean checkIfInQueue(Patient p) {
    // set nhsNumber equal to the nhsNumberLabel on the page
    String nhsNumber = nhsNumberLabel.getText();
    System.out.println("Checking if " + nhsNumber + " already in the queue");

    // create boolean to state whether a person is in the queue or not (defaults to false)
    boolean isInQueue = false;

    for (int i = 0; i < Queue.queue.size(); i++) {
      if (Queue.queue.size() == 0) {
        System.out.println("Queue is empty");
        isInQueue = false;
        break;
      } else if (Queue.queue.get(i).getNhsNumber() == p.getNhsNumber()) {
        System.out.println(p.getFirstName() + " is already in the queue (checkIfInQueue() method)");
        isInQueue = true;
        break;
      } else {
        System.out.println(p.getFirstName() + " is not is the queue (checkIfInQueue() method)");
        isInQueue = false;
      }
    }

    return isInQueue;
  }

谢谢, K

最佳答案

您可以以更标准和优雅的方式执行此操作。

覆盖 Patient 类中的 equals() 方法。

public boolean equals(Object obj){
    if(obj instanceof Patient){
        return ((ThisClass)obj.getNhsNumber().equals(this.getNhsNumber());
    }
    return false;
}

然后调用queue.contains()检查队列是否包含该对象。

Queue.queue.contains(p) // Call the contains method with the p object.

contains() 将遍历队列并通过调用 .equals() 检查对象是否等于您的 p 对象。

关于java - 检查对象是否已存在于 Java ArrayList 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29879942/

相关文章:

java - 我的 NetBeans 运行在什么 JVM 上

java - JUnit 错误 : Class names, 'org.junit.runner.JUnitCore' ,只有在显式请求注释处理时才被接受

java - BitSet valueOf 的作用是什么?

java - 减少数组的大小(通过创建新数组) - arrayList 是如何做到的?

Java ArrayList 帮助

javascript - 如何从 arrayList Jquery/Javascript 中删除重复的对象值

java - Selenium java 。将文本放入 div 元素 : element not interactable

java - Hibernate 版本控制/乐观锁定本身是否会使实例变脏

java - 将线程积添加到数组

java - 从两个可膨胀的 Edittext arrayList 获取值并计算值