Using emptyIterator in java

Can someone tell me what is the use of Iterator in real time in java? I am curious to know why this is necessary? such things as

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 ()

+7
java iterator
source share
1 answer

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
+7
source share

All Articles