StringUtils中的字符串判空
判空操作在我们工作用过是比较常用的一个操作,commons-lang3这个包为我们提供了两个判空的方法,分别是StringUtils.isEmpty(CharSequence cs)和StringUtils.isBlank(CharSequence cs),那有什么区别呢,今天就记录一下
1.maven地址
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
2.isEmpty()源码和用法
public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}
通过源码我们可以得知isEmpty() 方法校验的是字符串的长度和字符串是否是null,故空格将会通过校验。
public class StringOne {
public static void main(String[] args) {
System.out.println(StringUtils.isEmpty(null));//true
System.out.println(StringUtils.isEmpty(""));//true
System.out.println(StringUtils.isEmpty(" "));//false
System.out.println(StringUtils.isEmpty("hzm"));//false
}
}
3.isBlank()源码和用法
public static boolean isBlank(CharSequence cs) {
int strLen;
if (cs != null && (strLen = cs.length()) != 0) {
for(int i = 0; i < strLen; ++i) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
} else {
return true;
}
}
这个方法除了判断字符串是否为null和长度是否为零,还判断了是否为空格,如果是空格也返回true。
public class StringOne {
public static void main(String[] args) {
System.out.println(StringUtils.isBlank(null));//true
System.out.println(StringUtils.isBlank(""));//true
System.out.println(StringUtils.isBlank(" "));//true
System.out.println(StringUtils.isBlank("\n"));//true
System.out.println(StringUtils.isBlank("hzm"));//false
}
}