If语句 - null安全的变量顺序 [英] If statement - Variable order for null safety

查看:209
本文介绍了If语句 - null安全的变量顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想检查列表中的第一个元素是否等于是或否。

Assume I want to check if the first element from a list is equal to "YES" or "NO".

dummy_method(List<String> myList) {
    if(myList.isEmpty()) {
        return null; 
    }
    String firstListValue = myList.get(0).getStringValue(); 
    // Should I do this: 
    if ("YES".equalsIgnoreCase(firstListValue)) {
        return firstListValue; 
    }
    // OR this: 
    if (firstListValue.equalsIgnoreCase("YES")) {
        return firstListValue; 
    }
    // Do something else
}

其他单词:当我已经进行空检查时,如果A等于B 而,如果B等于A ,那么的顺序是否等于

In other words: Does the order of if A equals B versus if B equals A matter when I already have a null-check?

推荐答案

是的。这很重要。

您只检查了列表是否为非空。如果列表中的第一个元素是 null ,那么您将获得 NullPointerException at

You have only checked if the list is non-empty. If the first element in the list is null then you will get a NullPointerException at

firstListValue.equalsIgnoreCase("YES")

但是,如果你可以确保列表中的所有元素(或至少第一个元素)都是非null,然后两个语句都是等价的。

But, if you can ensure all the elements (or at least the first element) in the list are non-null, then both the statements are equivalent.

这篇关于If语句 - null安全的变量顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆