今天在写代码的时候用到了java.lang.String.isEmpty()的这个方法,以前也用过,今天突发奇想,就看了看源码,了解了解它的实现方法,总结出来,你们能够交流交流。html
一般状况下,咱们使用这个方法的时候是这样的:java
"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()上面也有体现:this
/** * 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数组的长度属性。spa
因此当字符串为""的时候"".isEmpty返回的是true,当字符串为null时null.isEmpty是会报错的。因此在使用isEmpty这个方法的时候,要先确保字符串时不能为null的。code
工做之余看一看源码仍是颇有帮助的,我看网上就有讨论null、""和isEmpty之间的区别,其实像这样的问题,咱们彻底能够经过阅读源码来解决。htm