1、概述
大家好,我是欧阳方超。
今天记录几个“判空”的问题。
2、各种判空
2.1、判断集合是否为空
在commons-collections4这个依赖中(jar包),具体坐标为:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>xxx</version>
</dependency>
有个工具类CollectionUtils,可以方便地判断集合是否为空,这里的“空”包括两层含义,一个是集合对象为null,另一个是集合对象的size为零,CollectionUtils.isEmpty()方法视这两个情况为空,以下没注释掉的array对象和注释掉的array对象均被视为空。
ArrayList<String> array = null;
//ArrayList<String> array = new ArrayList<>();
if (CollectionUtils.isEmpty(array)) {
System.out.println("空");
} else {
System.out.println("非空");
}
2.2、判断字符串是否为空
在commons-lang3依赖中(坐标如下),StringUtils类中的isEmpty()、isBlank()方法可以实现对字符串是否为空的判断。
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>xxx</version>
</dependency>
isEmpty()、isBlank()方法有些区别,如果是空格(单个或多个),isEmpty()判断非空而isBlank()判断为空,具体差异见下表:
字符串 | isEmpty()方法 | isBlank()方法 |
---|---|---|
“” | true | true |
null | true | true |
" " | false | true |
\t | false | true |
\n | true | ture |
3、总结
不积跬步无以至千里。
我是欧阳方超,把事情做好了自然就有兴趣了,如果你喜欢我的文章,欢迎点赞、转发、评论加关注。