您好,欢迎访问一九零五行业门户网

如何判断java对象是否为空

首先来看一下工具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): truecollectionutils.isempty(new arraylist()): truecollectionutils.isempty({a,b}): false
例2、判断集合是否不为空:
collectionutils.isnotempty(null): falsecollectionutils.isnotempty(new arraylist()): falsecollectionutils.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入门教程,欢迎在线学习!
以上就是如何判断java对象是否为空的详细内容。
其它类似信息

推荐信息