判断字符串为空
1、java.lang.string
isEmpty 判断字符串值为空
str.isEmpty()涉及兼容
先判断是否为对象,在判断引用是不是空字符串值
2、if(str == null || str.equals(""))
3、判断非空和非空白字符
if (str != null || !"".equals(str.trim())) {
//则字符串不为空或空格
}
判断非空(未判断非空白字符)
4、if(str != null && str.length() != 0) { }
效率高
//org.apache.commons.lang3.StringUtils;
//Checks if a CharSequence is empty ("") or null
public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}
//Checks if a CharSequence is whitespace, empty ("") or null.
public static boolean isBlank(CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (Character.isWhitespace(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
import java.util.List;
对象存在,判断size()==0,不存在报空指针
1、import java.util.List;
list.isEmpty()
list.isEmpty() 和 list.size()==0
没有区别 ,isEmpty()判断有没有元素,而size()返回有几个元素, 如果判断一个集合有无元素 建议用isEmpty()方法.比较符合逻辑用法
2、如果想判断list是否为空,可以这么判断:
if(null == list || list.size() ==0 ){
//为空的情况
}else{
//不为空的情况
}
3、等价2
if(list!=null && !list.isEmpty()){
//不为空的情况
}else{
//为空的情况
}