是否了解Collection.isEmpty()和Collection.size()== 0之间的区别? [英] Understanding the difference between Collection.isEmpty() and Collection.size() == 0?

查看:1417
本文介绍了是否了解Collection.isEmpty()和Collection.size()== 0之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了很多关于 isEmpty() size()> 0之间的区别的文章集合是否为空,并发现 isEmpty()的性能超过 size() 但我不容易理解为什么 isEmpty()的性能很好,即使在isEmpty()内部只有size == 0吗?

I have read so many article as on difference between isEmpty() and size() > 0 for check that collection is empty or not and found that isEmpty() have perfomance over size() but I could not understand easily why perfomance of isEmpty() is good even though inside isEmpty() is only size == 0 ?

我的问题是:


  1. 可以可以轻松解释在哪种情况下 isEmpty()更快,以及何时使用 isEmpty() size()函数用于检查集合是否为吗?

  1. Can any one explain easily in which scenario isEmpty() is faster as well as when to use isEmpty() and size() function for checking if collection is empty or not?

任何人都可以使用代码或其他方式(图,图表等)来解释此问题,以便任何初学者都能轻松理解吗?

Can any one explain this, using code or other way(Diagrams,graphs etc) so that any beginner can understand easily?


推荐答案

some 集合可能只使用在他们的 isEmpty()方法中的size()== 0 ,但这并不意味着它们都一样。 isEmpty()的默认实现只是检查 size()== 0 ,但是可以免费使用特定的集合

It might be that some collections just use size()==0 inside their isEmpty() method, but that doesn't mean that they all do. The default implementation of isEmpty() just checks whether size() == 0, but a particular collection is free to override this with something else if it's more efficient.

这里是一个很好的例子。 ConcurrentSkipListSet 文档说:

Here's a nice example. The ConcurrentSkipListSet documentation says:


请注意,与大多数集合不同,size方法不是固定时间的

Beware that, unlike in most collections, the size method is not a constant-time operation.

对于此类,您肯定要使用 isEmpty()而不是 size()== 0

For this class, you'd certainly want to use isEmpty() rather than size() == 0.

(要了解跳过列表为何如此,您需要仔细阅读跳过列表的工作原理,但是如果您想了解更多信息,请务必再次询问它们。)

(To understand why it's true for a skip list, you'd need to read up on how skip lists work, but do come back and ask another question about them if you want to know more.)

这篇关于是否了解Collection.isEmpty()和Collection.size()== 0之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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