今天在寫代碼的時候用到了java.lang.String.isEmpty()的這個方法,之前也用過,今天突發奇想,就看了看源碼,了解了解它的實現方法,總結出來,大家可以交流交流。
通常情況下,我們使用這個方法的時候是這樣的:
"hello wudb".isEmpty();
上面的代碼返回的是false,然后我們打開源碼分析,isEmpty()這個方法在很多類里面都有,我們今天分析的是String里面的,所以找到java.lang.String這個類,然后去找idEmpty()這個方法
/** * Returns {@code true} if, and only if, {@link #length()} is {@code 0}. * * @return {@code true} if {@link #length()} is {@code 0}, otherwise * {@code false} * * @since 1.6 */ public boolean isEmpty() { return value.length == 0; }
源碼里面已經所得很清楚了,當且僅當字符串的長度為0的時候返回的是true,否則返回的是false這兩個布爾類型的值,方法中出現的value是什么呢,繼續找
/** The value is used for character storage. */ private final char value[];
在String這個類的上方定義了一個char類型的一維數組,由此可以看到String的實現是基於char類型實現的(實際上是Unicode字符序列)。這一點在Stirng的另一個方法length()上面也有體現:
/** * Returns the length of this string. * The length is equal to the number of <a href="Character.html#unicode">Unicode * code units</a> in the string. * * @return the length of the sequence of characters represented by this * object. */ public int length() { return value.length; }
這里的字符串長度也是使用的char數組的長度屬性。
所以當字符串為""的時候"".isEmpty返回的是true,當字符串為null時null.isEmpty是會報錯的。所以在使用isEmpty這個方法的時候,要先確保字符串時不能為null的。
工作之余看一看源碼還是很有幫助的,我看網上就有討論null、""和isEmpty之間的區別,其實像這樣的問題,我們完全可以通過閱讀源碼來解決。