1.Java 判断字符串是否为空的方法
方法一:用的比较多
if( str == null || str.equals("")){
System.out.println("success");
}
方法二:效率高
if(str == null || str.length() == 0){
System.out.println("success");
}
方法三:用的比较多,工具类,需要先引入工具包。
引入依赖包如下:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>
import org.apache.commons.lang3.StringUtils;
if(StringUtils.isEmpty(str)){
System.out.println("success");
}
关于方法一踩过的坑如下:
(1)抄错了网上的代码,写成了如下示例(1),就报空指针异常。null在Java中就是不存在的意思,一个不存在的东西肯定没有.equals方法,所以报了空指针异常。
(2)先判断了null,走到str.equals()的时候就不会有null.equals这样的判断,就不会报错,一定要写str.equals(“”)的话,就需要把str.equals(“”)放在后面。
(3)“”.equals(str),""是字符串,字符串有equals()方法,所以也不会报错。
public class Judge {
public static void main(String[] args) {
String str = null;
if(str.equals("") || str == null){ //抛出空指针异常(1)
System.out.println("success");
}
if(str == null || str.equals("")){ //输出success(2)
System.out.println("success");
}
if("".equals(str) || str == null){ //输出success(3)
System.out.println("success");
}
}
}
总结判断思想:判断这个串是不是存在,如果存在是不是一个空串。
关于方法三:
它的源码如下,点进去其实是方法二。
public static boolean isEmpty(CharSequence value) {
return value == null || value.length() == 0;
}
2.Java 判断list是否为空的方法:
方法一:同样需要把null判断放在前面,不然会抛出空指针异常。
ArrayList list = new ArrayList();
list=null;
if(null == list || list.size() ==0 ){//输出success
System.out.println("success");
}
if(list.size() == 0 || null == list){//抛出空指针异常
System.out.println("success");
}
把list想象成一个装饼干的小罐头,null判断这个小罐头是不是存在的,list.size()判断里面有没有小饼干。
方法二:使用CollectionUtils工具类
import org.apache.commons.collections.CollectionUtils;
if (CollectionUtils.isEmpty(list)){
System.out.println("success");
}
它的源码为
public static boolean isEmpty(Collection coll) {
return coll == null || coll.isEmpty();
}
方法二其实是和法一是一样的,用来判空的时候,list.isEmpty()和list.size()==0 没有区别,isEmpty()判断有没有元素,而size()返回有几个元素,list.isEmpty()就表示没有元素,list.size() ==0时也是没有元素。如果判断一个集合有无元素, 建议用isEmpty()方法。
3.Java判断对象是否为空的方法
Cat cat = new Cat();
cat = null;
if (cat == null){//用null判断
System.out.println("success");//输出success
}