Java 检查集合非空和空条件的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19294014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to check collections not null & null conditions
提问by Java
we use collections like ArrayList,hashmap & many more.
我们使用 ArrayList、hashmap 等集合。
Number of times we have check condition like whether list is null or not.
我们检查条件的次数,例如列表是否为空。
We have many ways to chek whether our collection is null or not.
我们有很多方法可以检查我们的集合是否为空。
Different ways.
不同的方式。
1. if(list==null)
2. if(list.size()==0)
3. if(list.isEmpty())
Also sometimes we also need to check whether list is not null , so we normally check it by these ways
另外有时候我们也需要检查 list 是否不为 null ,所以我们通常通过这些方式来检查
1. if(list!=null)
2. if(list.size()>0)
3. if(!list.isEmpty())
Which is best condition or do we need to make some combination of these considering performance of program execution?
考虑到程序执行的性能,哪个是最好的条件,或者我们是否需要将这些组合起来?
回答by Masudul
null
means list
is initialized with null. null
list size
or isEmpty
will throw NullPointerException
. But, not null list
can be empty or size==0
null
手段list
初始化为空。null
列表size
或isEmpty
将抛出NullPointerException
。但是,not nulllist
可以为空或 size==0
(list!=null) != (list.size()==0)
size==0 and isEmpty is equivalent.
size==0 和 isEmpty 是等价的。
(list.size()==0) == list.isEmpty()
回答by Suresh Atta
Best combination would be
最好的组合是
if(list!=null && !list.isEmpty()){
//Yeah ,do something
}
One for null check, and then any thing there or not check
一个用于空检查,然后在那里检查或不检查任何事情
回答by harsh
There can be multiple approaches to handle this:
可以有多种方法来处理这个问题:
1: If code makes sure that collection cannot be null
by initializing it either in constructor or as field initializaiton then caller need not to ideally check for null
everywhere. Only isEmpty
check should suffice:
1:如果代码确保不能通过null
在构造函数中或作为字段初始化来初始化集合,则调用者不需要理想地检查null
所有地方。只有isEmpty
检查就足够了:
private List<Integer> numbers = new ArrayList<Integer>(); //or in constructor
// caller can then safely use
// 然后调用者可以安全地使用
if(numbers.isEmpty)
2: Alternatively write a utility method to have null
and empty
check, no need for size
check as it already happens inside isEmpty
call. Use this utility method elsewhere in code.
2:或者写一个实用的方法有null
和empty
检查,无需size
检查,因为它已经发生了内部isEmpty
通话。在代码的其他地方使用此实用方法。
public static boolean empty(Collection<?> col) {
return col == null || col.isEmpty();
}
回答by GGrec
It depends on your program structure. For example, I have a helper class called ArrayUtils
, in which I have an API that looks like this:
这取决于您的程序结构。例如,我有一个名为 的辅助类ArrayUtils
,其中有一个如下所示的 API:
public static <E> boolean isEmpty(final Collection<E> collection)
{
return collection == null || collection.isEmpty();
}
I use this one when I know that I may get a null
list, but when I'm absolutely sure it's not null
, I use only if ( collection.isEmpty )
. Improves code readability, too.
当我知道我可能会得到一个null
列表时,我会使用这个,但是当我绝对确定它不是时null
,我只使用if ( collection.isEmpty )
. 也提高了代码的可读性。
collection.size() > 1
is redundant, because you have the other APIs at your disposal.
collection.size() > 1
是多余的,因为您可以使用其他 API。
回答by Eel Lee
It really depends on what you want to do. If you want to be sure that a list exist AND has some elements then you would use
这真的取决于你想做什么。如果你想确保一个列表存在并且有一些元素,那么你可以使用
if (list != null && !list.isEmpty())
If I may give some advice, while returning collections, return by default an empty collection. That way you will avoid nulls.
如果我可以提供一些建议,在返回集合时,默认返回一个空集合。这样你就可以避免空值。
回答by Sean Patrick Floyd
1. if(list!=null)
You should make sure that is never the case!!
你应该确保永远不会发生这种情况!!
Read Effective Java 2nd Edition by Joshua Bloch
Item 43: Return empty arrays or collections, not nulls
阅读Joshua Bloch 撰写的 Effective Java 2nd Edition
第 43 条:返回空数组或集合,而不是空值
[...] In summary, there is no reason ever to return null from an array- or collection-valued method instead of returning an empty array or collection. The null-return idiom is likely a holdover from the C programming language, in which array lengths are returned separately from actual arrays. In C, there is no advantage to allocating an array if zero is returned as the length.
[...] 总之,没有理由从数组或集合值方法返回 null 而不是返回空数组或集合。null-return 习惯用法可能是 C 编程语言的保留,其中数组长度与实际数组分开返回。在 C 中,如果返回零作为长度,则分配数组没有任何优势。
In short, let your methods return Collections.emptyList()
instead of null and you've got one thing less to worry about.
简而言之,让您的方法返回Collections.emptyList()
而不是 null,您就不必担心一件事了。
2. if(list.size()>0)
3. if(!list.isEmpty())
That depends. For a simple collection such as ArrayList, they are equivalent. But what if your Collection is actually a live view of a Database query? Calling size() might me a very expensive operation, whereas isEmpty() will always be O(1). I'd say use isEmpty().
那要看。对于像 ArrayList 这样的简单集合,它们是等价的。但是,如果您的集合实际上是数据库查询的实时视图呢?调用 size() 可能是一个非常昂贵的操作,而 isEmpty() 将始终是 O(1)。我会说使用 isEmpty()。
Also see Jon Skeet's answer here: https://stackoverflow.com/a/11152624/342852
另请参阅 Jon Skeet 的回答:https: //stackoverflow.com/a/11152624/342852
回答by Stephen C
Number of times we have check condition like whether list is null or not.
我们检查条件的次数,例如列表是否为空。
For a start, a null
collection and an empty collection are different things. If you need to test if a collection is null
you need a differenttest to if you are trying to test if the collection is empty.
首先,null
集合和空集合是不同的东西。如果您需要测试集合是否为空,则null
需要不同的测试来测试集合是否为空。
Secondly, if a collection could be either null
or empty (and they "mean" the same thing, per your application design) then you have a problem in your design. You should most likely represent ... whatever it is you are trying to represent ... one way, and not either / both ways.
其次,如果一个集合可能是或者是null
空的(并且根据您的应用程序设计,它们“意味着”相同的事情),那么您的设计就有问题。你很可能应该代表......无论你试图代表什么......一种方式,而不是任何一种/两种方式。
Thirdly, it is generally best to use an empty collection rather than a null
, because you can treat an empty and non-empty collection uniformly. By contrast, a null
alwaysneeds to be handled as a special case. (And if you forget to handle the null
case, then you've got a potential for NullPointerExceptions
.)
第三,通常最好使用空集合而不是 a null
,因为您可以统一对待空集合和非空集合。相比之下, anull
总是需要作为特殊情况处理。(如果你忘记处理这个null
案子,那么你就有可能NullPointerExceptions
。)
Having said that ...
话说回来 ...
Which is best condition or do we need to make some combination of these considering performance of program execution?
考虑到程序执行的性能,哪个是最好的条件,或者我们是否需要将这些组合起来?
If you really need to deal with the case of a null
, then you've no choice but to test for null
.
如果您真的需要处理 a 的情况null
,那么您别无选择,只能测试null
.
For isEmpty()
versus size() == 0
:
对于isEmpty()
对size() == 0
:
the two predicates should give the same answer (unless you have an infinite lazy collection ...), but
in some cases
isEmpty()
couldbe faster, at least in theory.
这两个谓词应该给出相同的答案(除非你有一个无限的惰性集合......),但是
在某些情况下
isEmpty()
可能会更快,至少在理论上是这样。
The latter depends on the implementation of the collection type: specifically, on whether the size()
method needs to countthe collection elements. (I don't think that any of the standard collection classes have this property, but that's not to say that you won't find some class that does ...)
后者取决于集合类型的实现:具体来说,取决于该size()
方法是否需要对集合元素进行计数。(我不认为任何标准集合类都具有此属性,但这并不是说您找不到某些具有此属性的类...)
So the optimal predicate is most likely either:
所以最优谓词很可能是:
c != null && !c.isEmpty()
or
或者
!c.isEmpty()
depending on whether you (really) need to cater for nulls.
取决于您(真的)是否需要满足空值。
And the obvious corollary is that your application is likely to be more efficient ... as well as simpler and more robust ... if you don'tuse null
to represent empty collections. (If you need immutable empty collection objects, you can get them for free from methods / statics defined by the Collections
class.)
显而易见的推论是,您的应用程序可能会更高效……而且更简单、更健壮……如果您不用于null
表示空集合。(如果你需要不可变的空集合对象,你可以从Collections
类定义的方法/静态中免费获取它们。)
回答by Johnny
In Java8you can use Optionalto handle null cases properly. For example, both lists animalsNull
and animalWithNullElements
would be properly handled by the function filterList
:
在Java8 中,您可以使用Optional来正确处理空情况。例如,两个列表animalsNull
和animalWithNullElements
都将由函数正确处理filterList
:
List<String> animalsNull = null;
List<String> animalWithNullElements = new ArrayList<String>();
animalWithNullElements.add(0, null);
animalWithNullElements.add(1, "Guybrush Threepwood");
animalWithNullElements.add(2, null);
private static List<String> filterList(List<String> animals) {
return Optional.ofNullable(animals)
.orElseGet(Collections::emptyList)
.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
回答by magulla
If it you are owner of the codebase, I would avoid using such logic at all. Instead try to follow the model when your collection supplier can't return null but has a reference to Collections.emptyXXX or just regular empty container empty.
如果您是代码库的所有者,我会完全避免使用这种逻辑。相反,当您的集合供应商无法返回 null 但引用 Collections.emptyXXX 或只是普通的空容器为空时,请尝试遵循该模型。
回答by Serg
There is a useful util class called CollectionUtils
from Apache commons-collections
bundle. With using it the code will look like:
有一个CollectionUtils
从 Apachecommons-collections
包中调用的有用的 util 类。使用它后,代码将如下所示:
if(CollectionUtils.isEmpty(collection))
if(CollectionUtils.isEmpty(collection))
It looks nice and under the hood it has the same invocation:
它看起来不错,在引擎盖下它具有相同的调用:
public static boolean isEmpty(Collection coll) {
return coll == null || coll.isEmpty();
}
public static boolean isEmpty(Collection coll) {
return coll == null || coll.isEmpty();
}