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

时间:2015-04-26 15:59:34

标签: 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;
  }

感谢, ķ

3 个答案:

答案 0 :(得分:2)

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

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

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()将遍历队列并通过调用p检查对象是否与您的.equals()对象相同。

答案 1 :(得分:0)

对于非原始元素,您需要使用equals()代替==

此外,您应该阅读Javadoc of Set。此系列可以避免您检查是否已存储Patient并且表现会更好。

答案 2 :(得分:0)

    if (Queue.queue.size() == 0) {
        System.out.println("Queue is empty");
        isInQueue = false;
        break;
      } 
      >> This code does not serve purpose because the for loop already check the condition of 0.

    Modify like this
    for (int i = 0; i < Queue.queue.size(); i++) {
       String nhsnumber=Queue.queue.get(i).getNhsNumber();
       if (nhsnumber.equalIgnoreCase(p.getNhsNumber())==true) {
        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;
      }
      }

     >> isInQueue variable is also not used so remove the variable if its not used