检查列表是否为空的两种方法 - 差异?
Two ways to check if a list is empty - differences?
我有一个简短的问题。
假设我们有一个 List
,它是一个名为 list
的 ArrayList
。我们要检查列表是否为空。
有什么区别(如果有的话):
if (list == null) { do something }
和
if (list.isEmpty()) { do something }
我正在研究一个古老的代码(2007 年左右由其他人编写),它使用 list == null
结构。但是当我们有 list.isEmpty()
方法时为什么要使用这个结构...
第一个告诉您 list
变量是否已分配一个 List 实例。
第二个告诉您 list
变量引用的列表是否为空。
如果 list
为 null,则第二行将抛出 NullPointerException
.
如果你只想在列表为空时这样做,这样写更安全:
if (list != null && list.isEmpty()) { do something }
如果你想在列表为 null 或空时执行某些操作,你可以这样写:
if (list == null || list.isEmpty()) { do something }
如果你想在列表不为空时做一些事情,你可以这样写:
if (list != null && !list.isEmpty()) { do something }
if (list == null)
检查列表是否 null
。
if (list.isEmpty())
检查列表是否为空,如果列表是 null
并且你调用 isEmpty()
它会给你 NullPointerException
。
最好先检查列表是否为null
,然后再检查是否为空。
if(list !=null && ! list.isEmpty()){
// do your code here
}
另一种方法是使用Apache Commons Collections。
查看方法CollectionUtils.isEmpty()。更简洁。
对于 Spring 开发人员,还有另一种方法可以仅在一个条件下进行检查:
!CollectionUtils.isEmpty(yourList)
这允许您测试 list !=null 和 !list.isEmpty()
PS :应该从 org.springframework.util.CollectionUtils
导入它
我有一个简短的问题。
假设我们有一个 List
,它是一个名为 list
的 ArrayList
。我们要检查列表是否为空。
有什么区别(如果有的话):
if (list == null) { do something }
和
if (list.isEmpty()) { do something }
我正在研究一个古老的代码(2007 年左右由其他人编写),它使用 list == null
结构。但是当我们有 list.isEmpty()
方法时为什么要使用这个结构...
第一个告诉您 list
变量是否已分配一个 List 实例。
第二个告诉您 list
变量引用的列表是否为空。
如果 list
为 null,则第二行将抛出 NullPointerException
.
如果你只想在列表为空时这样做,这样写更安全:
if (list != null && list.isEmpty()) { do something }
如果你想在列表为 null 或空时执行某些操作,你可以这样写:
if (list == null || list.isEmpty()) { do something }
如果你想在列表不为空时做一些事情,你可以这样写:
if (list != null && !list.isEmpty()) { do something }
if (list == null)
检查列表是否 null
。
if (list.isEmpty())
检查列表是否为空,如果列表是 null
并且你调用 isEmpty()
它会给你 NullPointerException
。
最好先检查列表是否为null
,然后再检查是否为空。
if(list !=null && ! list.isEmpty()){
// do your code here
}
另一种方法是使用Apache Commons Collections。
查看方法CollectionUtils.isEmpty()。更简洁。
对于 Spring 开发人员,还有另一种方法可以仅在一个条件下进行检查:
!CollectionUtils.isEmpty(yourList)
这允许您测试 list !=null 和 !list.isEmpty()
PS :应该从 org.springframework.util.CollectionUtils
导入它