的使用

时间:2025-03-21 08:51:49

在校验一个String类型的变量是否为空时,可以使用方法,它可以校验三种情况:是否为null、是否为""、是否为空字符串(引号中间有空格)" "、制表符、换行符、换页符和回车。

(str); 当str不为空时,返回值为false。  

下面是该方法的源码:

public static boolean isBlank(CharSequence cs) {
        int strLen;
        if (cs != null && (strLen = ()) != 0) {
            for(int i = 0; i < strLen; ++i) {
                if (!((i))) {
                    return false;
                }
            }

            return true;
        } else {
            return true;
        }
    }

在业务代码中使用第三方jar的工具类去判断空,简化开发且方便阅读,类似的还有isEmpty()方法。

public static boolean isEmpty(CharSequence cs) {
        return cs == null || () == 0;
    }

通过源码可以看出:

没有忽略空格参数,是以是否为空和是否存在未判断依据。

进行了为空(字符串为空格、制表符、tab的情况)的判断。一般比较常用。

大家可以通过下面的例子进行体会:

("yyy") = false
("") = true
("   ") = false
 
("yyy") = false
("") = true
("   ") = true

常用的方法,但是时间久了会记忆模糊,特作出记录,高手可以忽略。。。