最近踩了一個String的isEmpty()這個方法的坑,就是當string的值為null的時候,s.isEmpty()會拋出一個空指針異常。所以去看了一下它的isEmpty()這個方法
public boolean isEmpty() {
return count == 0;
}
/** The count is the number of characters in the String. */
private final int count;
當count的值為0的時候返回true,反之false,前提是string已經創建了對象分配了內存,但是當string的值為null的時候是不會創建的,所以用這個方法區判斷就會出現空指針異常了。
isEmpty()可以用來判斷“”和new String()但不能用來判斷null.