本文介绍了Google Guava isNullOrEmpty用于收藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到Guava对字符串有isNullOrEmpty实用方法

I see that Guava has isNullOrEmpty utility method for Strings

Strings.isNullOrEmpty(str)

我们是否有类似的列表?类似

Do we have anything similar for Lists? Something like

Lists.isNullOrEmpty(list)

应相当于

list == null || list.isEmpty()

另外,我们对阵列有什么相似之处吗?类似

Also, do we have anything similar for Arrays? Something like

Arrays.isNullOrEmpty(arr)

应相当于

arr == null || arr.length == 0


推荐答案

不,这种方法可以在番石榴中不存在并且实际上在我们的想法墓地中。

No, this method does not exist in Guava and is in fact in our "idea graveyard."

我们不相信空或空是一个你真正想要的问题询问一个集合。

We don't believe that "is null or empty" is a question you ever really want to be asking about a collection.

如果一个集合可能为null,并且null应该被视为空,那么就预先解决所有这些歧义,像这样:

If a collection might be null, and null should be treated the same as empty, then get all that ambiguity out of the way up front, like this:

Set<Foo> foos = NaughtyClass.getFoos();
if (foos == null) {
  foos = ImmutableSet.of();
}

或者像这样(如果你愿意):

or like this (if you prefer):

Set<Foo> foos = MoreObjects.firstNonNull(
    NaughtyClass.getFoos(), ImmutableSet.<Foo>of());

之后,您只需使用 .isEmpty()像平常一样。在调用淘气的API时立即执行此操作,并且您已经将这种奇怪的东西放在身后,而不是让它无限期地继续下去。

After that, you can just use .isEmpty() like normal. Do this immediately upon calling the naughty API and you've put the weirdness behind you, instead of letting it continue on indefinitely.

如果null真的意味着空集合不会被退回给你,但是传递给你,你的工作很简单:只需抛出 NullPointerException ,然后让调用者变形。

And if the "null which really means empty collection" is not being returned to you, but passed to you, your job is easy: just let a NullPointerException be thrown, and make that caller shape up.

这篇关于Google Guava isNullOrEmpty用于收藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 06:13