今天在写代码的时候用到了java.lang.String.isEmpty()的这个方法,之前也用过,今天突发奇想,就看了看源码,了解了解它的实现方法,总结出来,大家可以交流交流。
通常情况下,我们使用这个方法的时候是这样的:
"hello wudb".isEmpty();
上面的代码返回的是false,然后我们打开源码分析,isEmpty()这个方法在很多类里面都有,我们今天分析的是String里面的,所以找到java.lang.String这个类,然后去找idEmpty()这个方法
/*** Returns {@codetrue} if, and only if, {@link#length()} is {@code0}.
*
*@return{@codetrue} if {@link#length()} is {@code0}, otherwise
* {@codefalse}
*
*@since1.6*/
public booleanisEmpty() {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 Unicode
* code units in the string.
*
*@returnthe length of the sequence of characters represented by this
* object.*/
public intlength() {returnvalue.length;
}
这里的字符串长度也是使用的char数组的长度属性。
所以当字符串为""的时候"".isEmpty返回的是true,当字符串为null时null.isEmpty是会报错的。所以在使用isEmpty这个方法的时候,要先确保字符串时不能为null的。
工作之余看一看源码还是很有帮助的,我看网上就有讨论null、""和isEmpty之间的区别,其实像这样的问题,我们完全可以通过阅读源码来解决。