java.util.List.isEmpty()
检查列表本身是否为 null
,还是我必须自己检查?
例如:
List<String> test = null;
if (!test.isEmpty()) {
for (String o : test) {
// do stuff here
}
}
这会抛出 NullPointerException
因为测试是 null
吗?
原文由 K‘’ 发布,翻译遵循 CC BY-SA 4.0 许可协议
您正在尝试在
null
参考上调用isEmpty()
方法(如List test = null;
)。这肯定会抛出NullPointerException
。您应该改为执行if(test!=null)
(首先检查null
)。方法
isEmpty()
返回true,如果ArrayList
对象不包含元素;否则为假(因为List
必须首先实例化,在你的情况下是null
)。你可能想看看 这个问题。