在開發中,我們判斷一個變量字符串string是否等於另一個常量字符串str時, 一般要判斷條件爲
if( string !=null && string.equals(str) ){ .... },
如果在string=null的情況下不判斷string !=null,則會報空指針異常NullPointerException。
作爲一個小技巧,省去代碼量的同時,直接判斷是否相等,我們可以直接寫成 if( str.equals(string) ){ ... },具體看個小例子。
import org.junit.Test;
public class TestT {
@Test
public void testEquals() {
String str = null;
String str1 = "aa";
// if("aa".equals(str1)){ //good
// if("aa".equals(str)){// bad
if (str.equals("aa")) {// NullPointerException
System.out.println("good");
} else {
System.out.println("bad");
}
}
}