当前位置: 移动技术网 > IT编程>开发语言>Java > Java中判断对象是否为空的方法的详解

Java中判断对象是否为空的方法的详解

2019年07月19日  | 移动技术网IT编程  | 我要评论

首先来看一下工具stringutils的判断方法:

一种是org.apache.commons.lang3包下的;

另一种是org.springframework.util包下的。这两种stringutils工具类判断对象是否为空是有差距的:

stringutils.isempty(charsequence cs); //org.apache.commons.lang3包下的stringutils类,判断是否为空的方法参数是字符序列类,也就是string类型

stringutils.isempty(object str); //而org.springframework.util包下的参数是object类,也就是不仅仅能判断string类型,还能判断其他类型,比如long等类型。

从上面的例子可以看出第二种的stringutils类更实用。

下面来看一下org.apache.commons.lang3的stringutils.isempty(charsequence cs)源码:

public static boolean isempty(final charsequence cs) {
    return cs == null || cs.length() == 0;
}

接下来是org.springframework.util的stringutils.isempty(object str)源码:

public static boolean isempty(object str) {
    return (str == null || "".equals(str));
}

基本上判断对象是否为空,stringutils.isempty(object str)这个方法都能搞定。

接下来就是判断数组是否为空

list.isempty(); //返回boolean类型。

判断集合是否为空

例1: 判断集合是否为空:

collectionutils.isempty(null): true
collectionutils.isempty(new arraylist()): true
collectionutils.isempty({a,b}): false

例2:判断集合是否不为空:

collectionutils.isnotempty(null): false
collectionutils.isnotempty(new arraylist()): false
collectionutils.isnotempty({a,b}): true

2个集合间的操作:
集合a: {1,2,3,3,4,5}
集合b: {3,4,4,5,6,7}

collectionutils.union(a, b)(并集): {1,2,3,3,4,4,5,6,7}
collectionutils.intersection(a, b)(交集): {3,4,5}
collectionutils.disjunction(a, b)(交集的补集): {1,2,3,4,6,7}
collectionutils.disjunction(b, a)(交集的补集): {1,2,3,4,6,7}
collectionutils.subtract(a, b)(a与b的差): {1,2,3}
collectionutils.subtract(b, a)(b与a的差): {4,6,7}

以上所述是小编给大家介绍的java中判断对象是否为空的方法详解整合,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网