Maybe some collections just use size()==0
inside their isEmpty()
method, but that doesn't mean they all do. The default implementation isEmpty()
by default checks to see if size() == 0
, but a particular collection can override this with something else if it is more efficient.
Here is a good example. The ConcurrentSkipListSet
documentation says:
Beware that, unlike most collections, the size method is not a constant time operation.
For this class, you certainly want to use isEmpty()
, not size() == 0
.
(To understand why this is true for the skip list, you will need to find out how the skip lists work, but go back and ask another question about them if you want to know more.)
source share