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));
}