是否注意过isEmpty 和 isBlank 区别?

栏目: IT技术 · 发布时间: 6年前

内容简介:做积极的人,而不是积极废人

点击上方 “ 匠心零度 ” ,选择“ 设为星标 ”

做积极的人,而不是积极废人

是否注意过isEmpty 和 isBlank 区别?

来源:http://h5ip.cn/ix9z

前言

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) 来执行判空操作,判断的条件更多更具体,特别是进行参数校验时,推荐使用。

END

如果读完觉得有收获的话,欢迎点【好看】,关注【匠心零度】,查阅更多精彩历史!!!

是否注意过isEmpty 和 isBlank 区别?

让我“ 好看 ”  是否注意过isEmpty 和 isBlank 区别?


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

Visual Thinking

Visual Thinking

Colin Ware / Morgan Kaufmann / 2008-4-18 / USD 49.95

Increasingly, designers need to present information in ways that aid their audiences thinking process. Fortunately, results from the relatively new science of human visual perception provide valuable ......一起来看看 《Visual Thinking》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具