• java判断空的方法


    字符串判空

    字符串为空分为两种情况:

    1)“”:表示分配了内存空间,值为空字符串,有值。
    2)null:未分配内存空间,无值,值不存在。
    为空的标准为:str == null 或 str.length()==0

    1.判断为空:
    • isEmpty()方法,判断是否为空,是否为空字符串(在String为null时,会出现空指针错误,isEmpty()方法底层是判断长度)
    • isBlank()方法,是判断字符串是否为空,空格、制表符、tab。
    public static boolean isEmpty(CharSequence cs) {
           return cs == null || cs.length() == 0;
       }
    
    public static boolean isBlank(CharSequence cs) {
            int strLen;
            if (cs != null && (strLen = cs.length()) != 0) {
            	//判断是否为空格、制表符、tab
                for(int i = 0; i < strLen; ++i) {
                    if (!Character.isWhitespace(cs.charAt(i))) {
                        return false;
                    }
                }
    
                return true;
            } else {
                return true;
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    2.判断不为空:

    isNotEmpty()、isNotBlank()
    推荐使用lang3下的StringUtiles工具类中
    StringUtils.isBlank()和StringUtils.isNotBlank(),它会过滤空格。

    List判空

    1、判断list不为空:

    方法1:list != null && !list.isEmpty()
    方法2:list != null && list.size() > 0

    注:
    list!=null:判断是否存在list,null表示这个list不指向任何的东西,如果为空时调用它的方法,那么就会出现空指针异常。
    list.isEmpty():判断list里是否有元素存在
    list.size():判断list里有几个元素
    所以判断list里是否有元素的最佳的方法是:
    if(list != null && !list.isEmpty()){
    //list存在且里面有元素
    }

    2、判断list为空:

    方法1:list == null || list.size() == 0

  • 相关阅读:
    家政服务接单小程序开发源码 家政保洁上门服务小程序源码 开源完整版
    全面升级,淘宝/天猫api接口大全
    cache2go-源码阅读
    el-tooltip那些事
    AIDL基本使用
    第六十七天 shell编程
    腾讯云服务器使用教程,手把手教你入门
    各大自动化测试框架对比
    Mathtype公式自动转Word自带公式
    python paramiko模块
  • 原文地址:https://blog.csdn.net/lib_w/article/details/126427463