JAVA判断各种类型数据是否为空

1、判断list是否为空(Map、Set同list)

[java]  view plain  copy
  1. if(list != null && list.size() != 0){  
  2. }  
  3.    
  4. if(list != null && !list.isEmpty()){  
  5. }  
  6.   
  7. list!=null:判断是否存在list,null表示这个list不指向任何的东西,如果这时候你调用它的方法,那么就会出现空指针异常。  
  8.   
  9. list.isEmpty():判断list里是否有元素存在    
  10.   
  11. list.size():判断list里有几个元素  
  12.   
  13.   
  14. 所以判断list里是否有元素的最佳的方法是:  
  15.   
  16. if(list != null && !list.isEmpty()){  
  17.   //list存在且里面有元素  
  18. }  
2、判断String类型数据是否为空

[html]  view plain  copy
  1. 直接用if( s.equals("")),if( !s.isEmpty()),if(s.length()>0)来判断:忽略了s为null的情况,s指向不确定的对象,无法调用一个确定的Sting对象的方法  
  2.   
  3. (1)str == null;  
  4. (2)"".equals(str);  
  5. (3)str.length <= 0;  
  6. (4)str.isEmpty();  
3、判断date类型数据是否为空

Date date=…… //实例化
if(date==null){
System.out.println("date为空");
}else{
System.out.println("date不为空");
}

你可能感兴趣的:(Java基础)