Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the difference between Collection.isEmpty() and Collection.size() == 0? [duplicate]

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?

like image 356
Kamlesh Kanazariya Avatar asked Dec 17 '14 12:12

Kamlesh Kanazariya


People also ask

What is difference between isEmpty and size in java?

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

Is isEmpty same as size 0?

Basically, in implementations of some lists the method isEmpty() checks if the size is zero (and therefore from the point of view of performance they are practically equivalent). In other types of lists (for example the linked lists), however, counting items require more time than to check if it is empty or not.

How do I know if a collection is empty?

The isEmpty() of java. util. Collection interface is used to check if the Collection upon which it is called is empty or not. This method does not take any parameter and does not returns any value.

What is the difference between isEmpty and empty?

Both methods are used to check for blank or empty strings in java. The difference between both methods is that isEmpty() method returns true if, and only if, string length is 0.


1 Answers

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

like image 108
chiastic-security Avatar answered Oct 12 '22 21:10

chiastic-security