You can use it in cases where the API you are implementing requires the iterator’s purchase logic to produce empty results. So instead of returning null, you are returning an empty iterator. Like you can use it to save memory and test.
An example that prevents null and returns some memory at the same time:
class LazyObjectInitialization { private Collection<String> items; public final Iterator<String> items() { if(items == null || items.isEmpty()) { return Collections.emptyIterator(); } return items.iterator(); } public final add(String item) { if(items == null) { items = new ArrayList<>(); } items.add(item); } }
In the above class, the items field is not initialized until an item is added. Therefore, to ensure the expected behavior in the items() method, we return an empty iterator. The benefits of this are as follows:
- Less memory consumption:
- The class allocates memory when it is really needed.
- Less memory
- Until we add something to the object, we will never create a new iterator instance.
- We never return null
Damian Leszczyński - Vash
source share