I'm wondering why there's an isEmpty() method in Java's List interface since there's a size() method. And when used as a loop guard, which one is better, list.isEmpty() or list.size == 0?
Asked
Active
Viewed 181 times
-3
-
Why wouldn't there be? – Kayaman Aug 19 '14 at 22:28
-
I seem to recall a duplicate, the implementation of isEmpty() was return size==0; in the oracle implementation. – Captain Giraffe Aug 19 '14 at 22:28
-
In terms of performance? Readability? Or in terms of some other criteria? – mostruash Aug 19 '14 at 22:29
-
In some implementations, isEmpty is cheaper than size - a linked list, for example. – Blorgbeard Aug 19 '14 at 22:29
-
1See http://stackoverflow.com/questions/1508975/why-is-list-size0-slower-than-list-isempty-in-java – ROMANIA_engineer Aug 19 '14 at 22:30
-
http://pmd.sourceforge.net/pmd-4.3.0/rules/design.html#UseCollectionIsEmpty – Engineer2021 Aug 19 '14 at 22:30
-
1Semantics makes the difference here if ( stuffs.isEmpty() ) conveys a lot more meaning than == 0. – Captain Giraffe Aug 19 '14 at 22:31
2 Answers
0
I'd say they are the same :
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}

Eran
- 387,369
- 54
- 702
- 768