工作中经常可以看到下面的代码片段:
if(str==null||str.trim().length()==0){......}
这段代码的作用是判断一个字符串是否为空值。代码虽简单,但这种方式有个问题:使用了trim()方法。
trim()方法本身没什么不好,只是被用错了地方。
我们看看trim()是怎么工作的。
public String trim() {intlen= count;intst =0;intoff = offset;/* avoid getfield opcode */char[] val = value;/* avoid getfield opcode */while ((st 0) || (len< count)) ? substring(st,len) : this; }
publicStringsubstring(intbeginIndex,intendIndex){if(beginIndex <0) {thrownewStringIndexOutOfBoundsException(beginIndex);}if(endIndex > count) {thrownewStringIndexOutOfBoundsException(endIndex);}if(beginIndex > endIndex) {thrownewStringIndexOutOfBoundsException(endIndex - beginIndex);}return((beginIndex ==0) && (endIndex == count)) ?this:newString(offset + beginIndex, endIndex - beginIndex,value); }
可以看到, 当字符串前后有空白字符时,trim()会生成一个新的String对象。
我们可以直接使用apache commons lang包中的StringUtils类的isEmpty()或isBlank()方法来判断字符串是否为空。
如果你不想引入第三方的jar包,想要自己实现,那么也可以参考apache的实现方式:
*
Checksifa CharSequenceisempty ("") ornull.
* ** StringUtils.isEmpty(null) =true* StringUtils.isEmpty("") =true* StringUtils.isEmpty(" ") =false* StringUtils.isEmpty("bob") =false* StringUtils.isEmpty(" bob ") =false** *
NOTE: This method changedinLang version2.0. * It no longer trims the CharSequence. * That functionalityisavailableinisBlank().
* *@paramcs the CharSequence to check, may benull*@return{@codetrue}ifthe CharSequenceisempty ornull*@since3.0Changed signature from isEmpty(String) to isEmpty(CharSequence) */publicstatic boolean isEmpty(CharSequence cs) {returncs ==null|| cs.length() ==0; }/** *Checks if a CharSequence is whitespace, empty ("") or null.
* ** StringUtils.isBlank(null) = true * StringUtils.isBlank("") = true * StringUtils.isBlank(" ") = true * StringUtils.isBlank("bob") = false * StringUtils.isBlank(" bob ") = false ** *@paramcs the CharSequence to check, may be null *@return{@codetrue} if the CharSequence is null, empty or whitespace *@since2.0 *@since3.0 Changed signature from isBlank(String) to isBlank(CharSequence) */publicstatic boolean isBlank(CharSequence cs) { int strLen;if(cs ==null|| (strLen = cs.length()) ==0) {returntrue; }for(int i =0; i < strLen; i++) {if(Character.isWhitespace(cs.charAt(i)) ==false) {returnfalse; } }returntrue; }
网友评论