Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of emptyIterator in java [duplicate]

Tags:

java

iterator

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

like image 987
user3366706 Avatar asked Oct 09 '14 22:10

user3366706


People also ask

How do you find the size of Iterables?

We can invoke the size() method of IterableUtils on an Iterable object to get its size.

How do I know if my Iterator is empty?

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.

What is an Iterator in Java?

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.


1 Answers

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

    • The class allocates memory only when it is really needed.
  • Smaller memory mutation

    • Until we add something to the object, we never create a new instance of the iterator.
  • We never return null.

like image 140
Damian Leszczyński - Vash Avatar answered Oct 21 '22 12:10

Damian Leszczyński - Vash