• isEmpty 和 isBlank 区别


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

    分析

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

     

     1 public static boolean isEmpty(String str) {
     2     return str == null || str.length() == 0;
     3 }
     4 
     5 public static boolean isNotEmpty(String str) {
     6     return !isEmpty(str);
     7 }
     8 
     9 public static boolean isBlank(String str) {
    10     int strLen;
    11     if (str != null && (strLen = str.length()) != 0) {
    12         for(int i = 0; i < strLen; ++i) {
    13             if (!Character.isWhitespace(str.charAt(i))) {
    14                 return false;
    15             }
    16         }
    17 
    18         return true;
    19     } else {
    20         return true;
    21     }
    22 }
    23 
    24 public static boolean isNotBlank(String str) {
    25     return !isBlank(str);
    26 }

    可以看到:

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

  • 相关阅读:
    最短母串
    noip模拟测试7
    linux下的对拍程序
    noip模拟测试6
    QWidget 前后位置设定
    C++编程规范_第5~13条 设计风格
    random /timer/sort 示例代码
    资料准备
    【转】三维动态数组 分配与释放
    批量修改文件名
  • 原文地址:https://www.cnblogs.com/love-feng/p/12340574.html
Copyright © 2020-2023  润新知