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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:35:03  来源:igfitidea点击:

Two ways to check if a list is empty - differences?

javalist

提问by dziki

I have a short question.

我有一个简短的问题。

Lets assume we have a Listwhich is an ArrayListcalled list. We want to check if the list is empty.

让我们假设我们有一个ListArrayList调用的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 == nullconstruction. But why use this construction when we have list.isEmpty()method...

我正在编写一个古老的代码(由其他人在 2007 年左右编写)并且它正在使用该list == null结构。但是当我们有list.isEmpty()方法时为什么要使用这种结构......

采纳答案by Eran

The first tells you whether the listvariable has been assigned a List instance or not.

第一个告诉您list变量是否已分配给 List 实例。

The second tells you if the List referenced by the listvariable is empty. If listis 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 nullor not.

if (list == null)检查列表是否null存在。

if (list.isEmpty())checking is list is empty or not, If list is nulland you call isEmpty()it will give you NullPointerException.

if (list.isEmpty())检查列表是否为空,如果列表是null,您调用isEmpty()它会给您NullPointerException

Its better to check whether list is nullor 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()。它更简洁。