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

  • 相关阅读:
    P4365 [九省联考2018]秘密袭击coat
    P3705 [SDOI2017]新生舞会 01分数规划+费用流
    P4313 文理分科 最小割
    P1707 刷题比赛
    P3994 高速公路 树形DP+斜率优化+二分
    P3384 【模板】树链剖分
    P4915 帕秋莉的魔导书
    P3690 【模板】Link Cut Tree (动态树)
    P3615 如厕计划
    loj #2538. 「PKUWC2018」Slay the Spire
  • 原文地址:https://www.cnblogs.com/love-feng/p/12340574.html
Copyright © 2011-2022 走看看