java判断String是不是为空探究
http://blog.****.net/lubiaopan/article/details/4720862
追求高质量的代码的同时,我们多多少少就得对java代码探究了,优质的,高性能的代码,无疑也是一个合格程序员的必备所学!
链接里已对String的判断做了详尽解释,如果单纯的比较String的为空或null的话,无疑是if(x != null && s.length() > 0),JDK6SE的string类的isEmpty()也是基于length()判断的,所以两者几乎没什么区别;
还有一种if(x != null && !"".equals(x)),之前一直用的这种,个人也倾向这种,但性能效率没上一种好,以后打算换上一种了,包括开源的那些框架源码也是第一种方法来判断的;
2.第三方的jar包commons-lang-2.3.jar 的StringUtils类
/**
* <p>Checks if a String is whitespace, empty ("") or null.</p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is null, empty or whitespace
* @since 2.0
*/
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
性能上较第一种还是差些,应该多了一些判断,性能影响大的是那个for循环,但此方法有了更强的逻辑,对空的字符串的处理。如果业务需要也是不错选择!
个人的一些小结,希望能共同学习!