Java 检查列表是否为空的两种方法 - 差异?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28089215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Two ways to check if a list is empty - differences?
提问by dziki
I have a short question.
我有一个简短的问题。
Lets assume we have a List
which is an ArrayList
called list
. We want to check if the list is empty.
让我们假设我们有一个List
被ArrayList
调用的list
。我们想检查列表是否为空。
What is the difference (if there is any) between:
之间有什么区别(如果有的话):
if (list == null) { do something }
and
和
if (list.isEmpty()) { do something }
I'm working on an ancient code (written around 2007 by someone else) and it is using the list == null
construction. But why use this construction when we have list.isEmpty()
method...
我正在编写一个古老的代码(由其他人在 2007 年左右编写)并且它正在使用该list == null
结构。但是当我们有list.isEmpty()
方法时为什么要使用这种结构......
采纳答案by Eran
The first tells you whether the list
variable has been assigned a List instance or not.
第一个告诉您list
变量是否已分配给 List 实例。
The second tells you if the List referenced by the list
variable is empty.
If list
is null, the second line will throw a NullPointerException
.
第二个告诉您list
变量引用的 List是否为空。如果list
为空,第二行将抛出一个NullPointerException
.
If you want to so something only when the list is empty, it is safer to write :
如果您只想在列表为空时才这样做,那么编写更安全:
if (list != null && list.isEmpty()) { do something }
If you want to do something if the list is either null or empty, you can write :
如果您想在列表为空或为空时执行某些操作,您可以编写:
if (list == null || list.isEmpty()) { do something }
If you want to do something if the list is not empty, you can write :
如果你想在列表不为空的情况下做一些事情,你可以写:
if (list != null && !list.isEmpty()) { do something }
回答by atish shimpi
if (list == null)
checking is list is null
or not.
if (list == null)
检查列表是否null
存在。
if (list.isEmpty())
checking is list is empty or not, If list is null
and you call isEmpty()
it will give you NullPointerException
.
if (list.isEmpty())
检查列表是否为空,如果列表是null
,您调用isEmpty()
它会给您NullPointerException
。
Its better to check whether list is null
or not first and then check is empty or not.
最好先检查列表null
是否为空,然后再检查是否为空。
if(list !=null && ! list.isEmpty()){
// do your code here
}
回答by josivan
Another approach is to use Apache Commons Collections.
另一种方法是使用Apache Commons Collections。
Take a look in method CollectionUtils.isEmpty(). It is more concise.
看看方法CollectionUtils.isEmpty()。它更简洁。