Pitfall - Using size to test if a collection is empty is inefficient.

suggest change

The Java Collections Framework provides two related methods for all Collection objects:

Both methods can be used to test for collection emptiness. For example:

Collection<String> strings = new ArrayList<>();
boolean isEmpty_wrong = strings.size() == 0; // Avoid this
boolean isEmpty = strings.isEmpty();         // Best

While these approaches look the same, some collection implementations do not store the size. For such a collection, the implementation of size() needs to calculate the size each time it is called. For instance:

By contrast, an isEmpty() method only needs to test if there is at least one element in the collection. This does not entail counting the elements.

While size() == 0 is not always less efficient that isEmpty(), it is inconceivable for a properly implemented isEmpty() to be less efficient than size() == 0. Hence isEmpty() is preferred.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Pitfalss - performance:
* Pitfall - Using size to test if a collection is empty is inefficient.

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
112 Pitfalss - performance
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap