Understanding the difference between Collection.is

2020-08-25 05:15发布

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 ?

My questions are :

  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?

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

3条回答
唯我独甜
2楼-- · 2020-08-25 05:55

Basically I had found that .size() can be O(1) or O(N), depending on the data structure; .isEmpty() is never O(N).

查看更多
放荡不羁爱自由
3楼-- · 2020-08-25 06:02

The top reasons for using isEmpty rather than size would be:

it is more expressive (the code is easier to read and to maintain)

it is faster, in some cases by orders of magnitude.

Detailed explanation here

++ same question asked here

查看更多
我只想做你的唯一
4楼-- · 2020-08-25 06:03

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.

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

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

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.)

查看更多
登录 后发表回答