Can anyone let me know what is the real time use of an Empty Iterator in java? I'm curious to know why is it needed? things like,
1. public static <T> Iterator<T> emptyIterator()
2. public static <T> ListIterator<T> emptyListIterator()
3. public static final <T> Set<T> emptySet(), etc..
source: http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#emptyIterator()
We can invoke the size() method of IterableUtils on an Iterable object to get its size.
l = [_ for _ in iterator] # If the list is not empty then the iterator had elements; else it was empty. if l : pass # Use the elements of the list (i.e. from the iterator) else : pass # Iterator was empty, thus list is empty.
An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term for looping. To use an Iterator, you must import it from the java. util package.
You can use an empty iterator in cases where an API that you implement requires an iterator, but some of your code's logic can yield no items in the result. In that case, instead of returning a null
, you return an empty iterator. You can also use an empty iterator to save some memory and for testing purposes.
Here is some example code that prevents returning null
and saves 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 field items
is not initialized until an element is added. So to provide expected behavior in method items()
we return an empty iterator. The benefit from this are as follow:
Smaller memory consumption
Smaller memory mutation
We never return null
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With