Java——判空

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/whm18322394724/article/details/82390198

  小菜今天整理了一下java判空的方法,也查了些许资料,想简单整理一下分享给大家,如有不对的地方欢迎大家留言,帮助小菜更快的成长!

StringUtils

  StringUtils工具类是用来做字符串的操作的,小菜知道的有两种,org.apache.commons.lang3包下的StringUtils类和org.springframework.util包下的StringUtils类,org.apache.commons.lang3包下的StringUtils类常用的判空有两种:isEmpty和isBlank。下面分别介绍一下。


1.org.apache.commons.lang3和org.springframework.util包中的StringUtils类的区别:
  org.apache.commons.lang3包下的StringUtils类,判断是否为空的方法参数是字符序列类,也就是string类型
  org.springframework.util包下的参数是object类,也就是不仅能判断string类型,还能判断其他类型,如long等类型(此包下的更实用)


2.isEmpty和isBlank的区别:
  这两个方法都是判断字符是否为空的,前者要求没有任何字符,后者要求是空白字符,isBank判断的空字符其实包括了isEmpty,也就是说isEmpty判断的范围比isBank小。而两者最大的区别就在于——isBank能判空格符而isEmpty不能。

3.例子:

String str1=null;
String str2="";
String str3="  ";
String str4="aa";

//isEmpty
System.out.println(StringUtils.isEmpty(str1));//——————true
System.out.println(StringUtils.isEmpty(str2));//——————true
System.out.println(StringUtils.isEmpty(str3));//——————false
System.out.println(StringUtils.isEmpty(str4));//——————false

//isBank
System.out.println(StringUtils.isBlank(str1));//——————true
System.out.println(StringUtils.isBlank(str2));//——————true
System.out.println(StringUtils.isBlank(str3));//——————true
System.out.println(StringUtils.isBlank(str4));//——————false 

CollectionUtils

  CollectionUtils是org.apache.commons.collections包中的工具类,提供了很多对集合的操作方法。

//(1)判空
CollectionUtils.isNotEmpty(resultApply)

//(2)并集
CollectionUtils.union(listA,listB);

//(3)交集
CollectionUtils.intersection(listA,listB);

//(4)补集
CollectionUtils.disjunction(listA,listB);

//(5)差集
CollectionUtils.subtract(listA,listB);

//(6)是否相等
CollectionUtils.isEqualCollection(listA,listB);

实践中的情况

  小菜在之前和前端对接接口时出现了这种情况,我的接口文档写的是:界面选择一个分类就传分类id,如果不选就不传或者传空,但前端却给我传的是两个单引号。接口对分类id判空我使用的是isEmpty,他传来的单引号用isEmpty做校验不管用,识别的是字符串,后来我用了isBank也不行,忘了具体哪的问题,后来我是这样暂时解决的问题

if ("''".equals(categoryId) || StringUtil.isEmpty(labelIds) ) {
    categoryId=null;
}

猜你喜欢

转载自blog.csdn.net/whm18322394724/article/details/82390198