检查列表是否为空的两种方法-差异? [英] Two ways to check if a list is empty - differences?

查看:80
本文介绍了检查列表是否为空的两种方法-差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简短的问题.

让我们假设我们有一个List,这是一个称为listArrayList.我们要检查列表是否为空.

Lets assume we have a List which is an ArrayList called list. We want to check if the list is empty.

两者之间有什么区别(如果有)

What is the difference (if there is any) between:

if (list == null) { do something }

if (list.isEmpty()) { do something }

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

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...

推荐答案

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

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

第二个告诉您list变量引用的列表是否为空. 如果list为null,则第二行将抛出NullPointerException.

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.

如果您只想在列表为空时这样做,则写起来更安全:

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 }

这篇关于检查列表是否为空的两种方法-差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆