我在一個項目工作(空==對象),或者如果(對象== NULL)有類似下面是正確的比較一樣,如果在Java中
if(null == object)
{
//do something
}
相同的是它作爲
聲明if(object == null){
// do something
}
舉一些例子,以便兩者相同或不同。
我在一個項目工作(空==對象),或者如果(對象== NULL)有類似下面是正確的比較一樣,如果在Java中
if(null == object)
{
//do something
}
相同的是它作爲
聲明if(object == null){
// do something
}
舉一些例子,以便兩者相同或不同。
運營商==
是對稱的。
x == null
等於null == x
。但使用第一種方式更具可讀性和習慣性。
還有其他的方法中的對象以檢查空值:
1. boolean Objects.nonNull(Object obj) // obj != null
2. T Objects.requireNonNull(T obj) // checks out obj and returns it if it isn't null
實施例:
String v = "value";
System.out.println(v == null ? null : v);
System.out.println(null == v ? null : v);
輸出:
value
value
在這個特定情況下沒有區別。風格的問題。第一種方式是編碼通常編寫爲Yoda style以避免空指針。但是這種情況是一樣的。
示例從維基
String myString = null;
if (myString.equals("foobar")) { /* ... */ }
// This causes a NullPointerException in Java
隨着尤達條件:
String myString = null;
if ("foobar".equals(myString)) { /* ... */ }
// This is false, as expected
注意避免的NullPointerException並不總是一個優點。覆蓋它們可能會導致其他錯誤或需要更多時間來調試代碼。
雖然這是相當明顯的那兩個object == null
一個d null == object
是相同的,使用後者的原因是意外避免使用賦值而不是比較。
在Java中,由於在測試表達式中只能使用boolean
s,所以發生這種情況的情況有限。
考慮
Object x = null;
int y = 0;
if (x = null) {} //Error (Good catch)
if (null = x) {} //Error (Of course, make no sense)
if (y = 0) {} //Error (Good catch)
if (0 = y) {} //Error (Of course, make no sense)
現在考慮
Boolean x = false;
boolean y = false;
if (x = false) {} //OK (But maybe not what intended)
if (false = x) {} //Error (Good catch)
if (y = false) {} //OK (But maybe not what intended)
if (false = y) {} //Error (Good catch)
所以尤達風格避免犯這種錯誤。
個人認爲我覺得尤達風格幼稚。處理賦值運算符和相等運算符是程序員必須能夠做到的事情,即使在考慮他們離開車鑰匙的位置時也是如此。
不僅幼稚..危險有時:) –
他們是相同的,因爲兩者都需要評估 –