在java中验证null和empty的集合的最佳实践 [英] Best practice to validate null and empty of a collection in java

查看:669
本文介绍了在java中验证null和empty的集合的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要验证集合是否为空, null

I want to verify whether a collection is empty and null. Could anyone please let me know the best practice.

目前我正在检查如下。

if(null == sampleMap || sampleMap.isEmpty())
{
  // do something
} 
else
{
  // do something
}


推荐答案

如果您在项目中使用Apache Collections库,您可以使用 CollectionUtils.isEmpty MapUtils.isEmpty 方法分别检查集合或映射是空的还是空的(即它们是空安全的)。

If you use the Apache Collections library in your project, you may use the CollectionUtils.isEmpty and MapUtils.isEmpty methods which respectively check if a collection or a map is empty or null (i.e. they are "null-safe").

这些方法背后的代码或多或少是什么user @

The code behind these methods is more or less what user @icza has written in his answer.

不管你做什么,记住你编写的代码越少,代码就越少,代码越复杂,代码越少。

Regardless of what you do, remember that the less code you write, the less code you need to test as the complexity of your code decreases.

这篇关于在java中验证null和empty的集合的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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