If语句 - null安全的变量顺序

nor*_*ner 1 java variables if-statement

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

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
}
Run Code Online (Sandbox Code Playgroud)

换句话说:当我已经进行空检查时,A的顺序是否等于B,B是否等于A的顺序?

use*_*er7 5

是.这很重要.

您只检查列表是否为非空.如果列表中的第一个元素为null,那么您将得到一个NullPointerExceptionat

firstListValue.equalsIgnoreCase("YES")
Run Code Online (Sandbox Code Playgroud)

但是,如果您可以确保列表中的所有元素(或至少第一个元素)都是非null,那么这两个语句都是等效的.