是否注意过 isEmpty 和 isBlank 区别?

2019 年 10 月 11 日 ImportNew

(给ImportNew加星标,提高Java技能)

转自:简书,作者:希希里之海

www.jianshu.com/p/98e7593ca0e2


前言


org.apache.commons.lang.StringUtils 类提供了 String 的常用操作,最为常用的判空有如下两种 isEmpty(String str) isBlank(String str)


分析


我们通过源码来分析区别:


public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}

public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}

public static boolean isBlank(String str) {
int strLen;
if (str != null && (strLen = str.length()) != 0) {
for(int i = 0; i < strLen; ++i) {
if (!Character.isWhitespace(str.charAt(i))) {
return false;
}
}

return true;
} else {
return true;
}
}

public static boolean isNotBlank(String str) {
return !isBlank(str);
}



可以看到:


  1. StringUtils.isEmpty(String str)判断某字符串是否为空,为空的标准是 str==null 或 str.length()==0

  2. StringUtils.isBlank(String str)判断某字符串是否为空或长度为 0 或由空白符 (whitespace) 构成

  3. StringUtils.isNotEmpty(String str)等价于!isEmpty(String str)

  4. StringUtils.isNotBlan(String str)等价于!isBlank(String str)


建议


StringUtils.isBlank(String str) 来执行判空操作,判断的条件更多更具体,特别是进行参数校验时,推荐使用。


另外,你们项目是否有isEmptyisBlank混用的情况?


推荐阅读

(点击标题可跳转阅读)

手把手实现一条延时消息

Tomcat 在 SpringBoot 中是如何启动的

Spring 的 BeanUtils 的 copyProperties 方法需要注意的点


看完本文有收获?请转发分享给更多人

关注「ImportNew」,提升Java技能

好文章,我在看❤️

登录查看更多
0

相关内容

【2020新书】实战R语言4,323页pdf
专知会员服务
98+阅读 · 2020年7月1日
【高能所】如何做好⼀份学术报告& 简单介绍LaTeX 的使用
【2020新书】Kafka实战:Kafka in Action,209页pdf
专知会员服务
65+阅读 · 2020年3月9日
算法与数据结构Python,369页pdf
专知会员服务
160+阅读 · 2020年3月4日
【新书】Java企业微服务,Enterprise Java Microservices,272页pdf
Keras作者François Chollet推荐的开源图像搜索引擎项目Sis
专知会员服务
29+阅读 · 2019年10月17日
【关关的刷题日记60】Leetcode 437. Path Sum III
【 关关的刷题日记53】 Leetcode 100. Same Tree
专知
10+阅读 · 2017年12月1日
【LeetCode 136】 关关的刷题日记32 Single Number
【LeetCode 500】关关的刷题日记27 Keyboard Row
专知
3+阅读 · 2017年11月5日
The Evolved Transformer
Arxiv
5+阅读 · 2019年1月30日
Arxiv
3+阅读 · 2018年10月18日
The Matrix Calculus You Need For Deep Learning
Arxiv
12+阅读 · 2018年7月2日
Arxiv
5+阅读 · 2015年9月14日
VIP会员
相关VIP内容
【2020新书】实战R语言4,323页pdf
专知会员服务
98+阅读 · 2020年7月1日
【高能所】如何做好⼀份学术报告& 简单介绍LaTeX 的使用
【2020新书】Kafka实战:Kafka in Action,209页pdf
专知会员服务
65+阅读 · 2020年3月9日
算法与数据结构Python,369页pdf
专知会员服务
160+阅读 · 2020年3月4日
【新书】Java企业微服务,Enterprise Java Microservices,272页pdf
Keras作者François Chollet推荐的开源图像搜索引擎项目Sis
专知会员服务
29+阅读 · 2019年10月17日
相关论文
The Evolved Transformer
Arxiv
5+阅读 · 2019年1月30日
Arxiv
3+阅读 · 2018年10月18日
The Matrix Calculus You Need For Deep Learning
Arxiv
12+阅读 · 2018年7月2日
Arxiv
5+阅读 · 2015年9月14日
Top
微信扫码咨询专知VIP会员