java - if 语句中的多个 OR 条件

标签 java

我创建了一个方法,该方法使用迭代器来迭代映射,并且对于每一对,它都会使用许多 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/

相关文章:

java.lang.NullPointerException Sun PetStore CatalogFacade

java - 在java中从catch/finally返回值?

java - 运行所有类并使用 Maven 提取信息

java - Spring 安全 : forcing https using annotations?

java - Android 中的运动检测器

java - Java中调用主类中的方法和其他类的区别

java - 按升序排列列表中的元素(首先是按递增方式排列的百分比,然后是不区分大小写的字母)

java - 在 Windows 上安装 Jenkins 作为服务

java - 数据库字符集 UTF16 未显示正确的字符

java - 应用程序在启动时崩溃,尝试查看登录屏幕是否存在文件