tags:

views:

517

answers:

3
+1  Q: 

Java Iterators

What is an external and internal iterator in Java ?

A: 

It is about who controls the iteration.

Other details are in this question What are the benefits of the Iterator interface in Java?

VonC
+3  A: 

I found this description:

External vs. internal iterators.

External Iterators - when the iteration is controlled by the collection object we say that we have an external Iterator.

In languages like .net on java it's very easy to create external iterators. In our classical implementation an external iterator is implemented. In the following example an external iterator is used:

// using iterators for a clloection of String objects:
// using in a for loop
for (Iterator it = options.iterator(); it.hasNext(); ) {
   String name = (String)it.next();
   System.out.println(name);
}

// using in while loop
Iterator name = options.iterator();
    while (name.hasNext() ){
      System.out.println(name.next() );
    }

// using in a for-each loop (syntax available from java 1.5 and above)
    for (Object item : options)
        System.out.println(((String)item));

Internal Iterators - When the iterator controls it we have an internal iterator

On the other side implementing and using internal iterators is really difficult. When an internal iterator is used it means that the code is be run is delegated to the aggregate object. For example in languages that offer support for this is easy to call internal iterators:

collection do: [:each | each doSomething] (Smalltalk)

The main idea is to pass the code to be executed to the collection. Then the collection will call internally the doSomething method on each of the components. In C++ it's possible to send the doMethod method as a pointer. In C# .NET or VB.NET it is possible to send the method as a delegate. In java the Functor design pattern has to be used. The main idea is to create a base Interface with only one method (doSomething). Then the method will be implemented in a class which implements the interface and the class will be passed to the collection to iterate. For more details see the Functor design pattern.

Chris Kimpton
+1  A: 

Real Short Answer aka Google it

A quick Google search could have given you the answer: http://www.google.com/search?hl=en&q=external+iterator&btnG=Google+Search&aq=f&oq=

Longer answer

External Iterator

When you get an iterator and step over it, that is an external iterator


for (Iterator iter = var.iterator(); iter.hasNext(); ) {
  Object obj = iter.next();
  // Operate on obj
}

Internal Iterator

When you pass a function object to a method to run over a list, that is an internal iterator


var.each( new Functor() {
  public void operate(Object arg) {
    arg *= 2;
  }
});
Johann Zacharee