java中经常会把null和isEmpty()用混掉,但其实只要记清楚它们的概念就不会在弄混了!
null:指的是值为空,没有分配空间
isEmpty():判断是否有值,而不是判断是否为空,只能判断 有分配空间 的,不能判断没有分配空间的
示例代码
public class test {
public static void main(String[] args) {
Map mapNull = null;
Map map = new HashMap();
test(mapNull);
test(map);
}
public static void test(Map map) {
if (map == null) {
System.out.println("null");
}
if (map != null) {
System.out.println("no null");
}
try {
if (map.isEmpty()) {
System.out.println("kong bu kong");
}
if (!map.isEmpty()) {
System.out.println("bu kong");
}
} catch (Exception e) {
System.out.println(e);
}
}
}
运行结果
null
java.lang.NullPointerException
no null
kong bu kong
看结果可以知道,当mapNull为null的时候**isEmpty()**执行结果出现空指针错误,而map因为有空间,所以执行有结果。
见解有限,有误欢迎提出。