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

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

问题描述

我想验证集合是否为空, null 。谁能告诉我最佳做法。

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

目前,我正在检查如下:

Currently, I am checking as below:

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


推荐答案

如果使用 Apache Commons Collections 库,您可以使用 CollectionUtils。 isEmpty MapUtils.isEmpty()分别检查集合或地图为空的的方法null (即它们是空值安全的)。

If you use the Apache Commons 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").

这些方法背后的代码或多或少是用户@icza在他的答案中写的。

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和空集合的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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