我创建了一个方法,该方法使用迭代器来迭代映射,并且对于每一对,它都会使用许多 OR 条件评估语句。如果条件为真,则会将该对的对象(通知对象)添加到列表(异常)中。但是,在编译时,编译器会在此方法处给出 NullPointerException 异常。根据我的调查,似乎 if 语句有问题,但我不明白为什么。有人可以帮我吗?谢谢!
public List<Notification> getAnomalies(NotificationSearchCriteria notificationSearchCriteria) {
Map<String,Notification> messageList = new HashMap<String,Notification>();
List<Notification> anomalies = new ArrayList<Notification>();
Iterator iterator = messageList.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry pairs = (Map.Entry)iterator.next();
Notification message = (Notification) pairs.getValue();
if(message.getDescription().equals(notificationSearchCriteria.getDescription())||message.getSubjectName().equals(notificationSearchCriteria.getSubjectName())||message.getNotificationSubject().toString().equals(notificationSearchCriteria.getNotificationSubject().toString())||message.getNotificationType().toString().equals(notificationSearchCriteria.getNotificationType().toString())){
anomalies.add(message);
}
}
}
return anomalies;
}
最佳答案
这很可能是由 message
上的方法之一引起的返回空值。例如,如果 message.getDescription()
返回 null,则 message.getDescription().equals(<something>)
会抛出 NullPointerException
,因为您无法在 null 对象上调用其他方法。
有多种方法可以解决此问题。首先,我建议检查您的对象以查看哪些对象可以返回空值并添加适当的处理代码。
更一般地说,我总是建议对您知道不为空的变量调用 equals 以避免这些问题。例如
if ("accept".equals(command)) {
// do something
}
通常优于
if (command.equals("accept")) {
// do something
}
因为第二个可能会通过 NPE,而第一个永远不会。
关于java - if 语句中的多个 OR 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14775475/