Java判空和值比较

1.Java判断List是否为空

 public static void main(String[] args) {
        List<Role> roleList = new ArrayList<>(); //已经实例化roleList!=null
        if(roleList==null){
            System.out.println("roleList为空");
        }
        if(roleList.size()>=0){
            System.out.println("roleList的元素个数大于等于0"+roleList.size());
        }
        if(roleList.isEmpty()){//如果为空,则[]
            System.out.println("roleList为[]");
        }
    }

由于我们将具体的 List实例化,所以执行校验方法后,实际上list已经被实例化了,所以如果使用 roleList != null来进行判断,这就会导致一直返回 true,所以我们将判断语句改为 if ( !roleList.isEmpty())或者if(roleList.size()>0)就可以了

那么在我们实际开发中可以这样搭配,先判断是否已经分配空间,防止isEmpty判空时空指针异常,同时满足集合中没有元素

if(roleList!= null && !roleList.isEmpty()){ //if(roleList!= null &&roleList.size()>0)
   //不为空执行的代码
}else{
   //为空执行的代码
}

2.Java判断String类型是否为空 

String对象中有一个isEmpty的方法判断是否为空,其实isEmpty完全等同于string.length()==0,注意如果String本身是null,那么使用string.isEmpty()会报空指针异常(NullPointerException)判断一个String为空的最安全的方法,还是string ==null || string.isEmpty()

工具StringUtils的判断方法: 

org.springframework.util包下的。

StringUtils.isEmpty(Object str); /**org.springframework.util包下的参数是Object类,也就是不仅仅能判断String类型,还能判断其他类型,比如Long等类型。*/

public static boolean isEmpty(Object str) { //源码
        return (str == null || "".equals(str));
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值