Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
575 views
in Technique[技术] by (71.8m points)

java - Google Guava isNullOrEmpty for collections

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)

which should be equivalent to

list == null || list.isEmpty()

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

Arrays.isNullOrEmpty(arr)

which should be equivalent to

arr == null || arr.length == 0
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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());

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...