Iterator

=Iterator Pattern:= The description of the Iterator Pattern is:



Iterators allow sequential access of elements in a collection of objects without exposing its underlying code. What does this mean? If you have a list object and you wish to move through each element in the list sequentially and maintain your current place in the list, an iterator seems appropriate. Iterator patterns have been around a long time. In early Visual Basic, iterators came in the form of record sets with methods to move through the record set and keep the current row as the placeholder. Earlier than that, iterators in different forms existed in other languages. Almost anyone familiar with coding languages has used an iterator in some form.

The Iterator pattern has two classes that are associated with it: the Aggregate and the Iterator. The aggregate is a collection or aggregate object of some type whose elements we wish to iterate through. We use the iterator as a tool to move through the aggregate elements and keep track of the progress.

The Iterator pattern allows a client object to access the contents of a container in a sequential manner, without having any knowledge about the internal representation of its contents.

The term container, used above, can simply be defined as a collection of data or objects. The objects within the container could in turn be collections, making it a collection of collections. The Iterator pattern enables a client object to traverse through this collection of objects (or the container) without having the container to reveal how the data is stored internally.

To accomplish this, the Iterator pattern suggests that a Container object should be designed to provide a public interface in the form of an Iterator object for different client objects to access its contents. An Iterator object contains public methods to allow a client object to navigate through the list of objects within the container.

One of the most common data structures in software development is what is generic called a collection. A collection is just a grouping of some objects. They can have the same type or they can be all cast to a base type like object. A collection can be a list, an array, a tree and the examples can continue.

But what is more important is that a collection should provide a way to access its elements without exposing its internal structure. We should have a mechanism to traverse in the same way a list or an array. It doesn't matter how they are internally represented.

The idea of the iterator pattern is to take the responsibility of accessing and passing through the objects of the collection and put it in the iterator object. The iterator object will maintain the state of the iteration, keeping track of the current item and having a way of identifying what elements are next to be iterated.

The iterator pattern allows us to:
 * Access contents of a collection without exposing its internal structure.
 * Support multiple simultaneous traversals of a collection.
 * Provide a uniform interface for traversing different collection.

Iterators in Java
One of the simplest iterators available in Java is the java.sql.ResultSet class, which is used to hold database records. This class offers a method next for navigating along rows and a set of getter methods for column positioning. Java also offers an interface Enumeration as part of the java.util package which declares the methods listed in.



Concrete iterators can be built as implementers of the Enumeration interface by providing implementation for its methods. In addition, the java.util.Vector class offers a method: public final synchronized Enumeration elements ; that returns an enumeration of elements or objects. The returned Enumeration object works as an iterator for the Vector object. The Java Enumeration interface methods listed in the table above can be used on the returned Enumeration object to sequentially fetch elements stored in the Vector object. Besides the Enumeration interface, Java also offers the java.util.Iterator interface. The Iterator interface declares three methods:

Similar to the Enumeration interface, concrete iterators can be built as implementers of the java.util.Iterator interface. Though it is considered useful to employ existing Java iterator interfaces such as Iterator or Enumeration, it is not necessary to utilize one of these built-in Java interfaces to implement an iterator. One can design a custom iterator interface that is more suitable for an application need.



Filtered Iterators
In the case of the java.util.Vector class, its iterator simply returns the next element in the collection. In addition to this basic behavior, an iterator may be implemented to do more than simply returning the next object in line. For instance, an iterator object can return a selected set of objects (instead of all objects) in a sequential order. This filtering can be based on some form of input from the client. These types of iterators are referred to as filtered iterators.

Internal versus External Iterators
An iterator can be designed either as an internal iterator or as an external iterator.

Internal iterators

 * The collection itself offers methods to allow a client to visit different objects within the collection. For example, java.util.ResultSet class contains the data and also offers methods such as next to navigate through the item list.
 * There can be only one iterator on a collection at any given time.
 * The collection has to maintain or save the state of iteration.

External iterators

 * The iteration functionality is separated from the collection and kept inside a different object referred to as an iterator. Usually, the collection itself returns an appropriate iterator object to the client depending on the client input. For example, the java.util.Vector class has its iterator defined in the form of a separate object of type Enumeration. This object is returned to a client object in response to the elements method call.
 * There can be multiple iterators on a given collection at any given time.
 * The overhead involved in storing the state of iteration is not associated with the collection. It lies with the exclusive Iterator object.

Iterator and multithreading
Several problems may appear when collections are added from different threads. First of all let's see which the basic steps when using an iterator are: It seems that the iterator does not raise special problems when a collection is used from different threads. Of course here we are talking about an "seems". To reformulate the iterator does not raise special problems when the collection used from different threads as long the collection is not changed. Let's analyze each case: The main task when creating a multithreading iterator is to create a robust iterator (that allows insertions and deletions without affection transversal). Then the blocks which are changing or accessing resources changed by another thread have to be synchronized.
 * Step one: the collection return a new iterator. Usually this step is not affected when it is used in multithreading environments because it returns a new iterator object.
 * Step two: The iterator is used for iterating through the objects. Since the iterators are different objects this step is not a problematic one in multithreading environments.
 * A new element is added to the collection (at the end). The iterator should be aware of the new size of the collection and to iterate till the end.
 * A new element is added to the collection before the current element. In this case all the iterators of the collection should be aware of this. The same actions should occur when an element is removed from the collection. The iterators should be aware of the changes.

Comparison to Similar Patterns
The Iterator pattern can be compared to the Memento pattern in the way it encapsulates the functionality of the aggregate and moves this logic to another class object, maintaining the state of the aggregate inside the iterator. This works much like the Memento pattern, which keeps state in the memento object until it is needed again. However, in the Memento the state is preserved as it was when removed from the originator. In the Iterator the state is changed directly inside the iterator. The iterator acts as an intermediary between the aggregate and itself, in effect acting as a mediator for itself, similar to the Mediator pattern. Similar Patterns to the Iterator Pattern are: Composite pattern, Mediator pattern, Memento pattern.

In the code sample below, we will create a main class that will be the type corporation, named Google. After that we will create class that will iterate with the main class, such as USA, Latin America, and psm. They do not interact all the same way, but they will iteract with the main class Google in a way or another.

//**Code sample 1: Filename: TestGogle.java**// code format="java" import java.util.ArrayList; import java.util.Iterator;

public class TestGoogle { public static void main(String args[]) { Google corporation = new Google;

// here we add the different regions that will interact with the main class Google that is of a type corporation Region usa = new Region("United States"); usa.add(new ProjectSoftwareManager("Ronald Reagan", "United States")); usa.add(new ProjectSoftwareManager("George Bush", "United States")); usa.add(new ProjectSoftwareManager("William Clinton", "United States"));

Region latinamerica = new Region("Latin America"); latinamerica.add(new ProjectSoftwareManager("Roberto Gonzalez", "Latin America")); latinamerica.add(new ProjectSoftwareManager("Luiz Sosa", "Latin America")); latinamerica.add(new ProjectSoftwareManager("Daniel Passarela", "Latin America")); latinamerica.add(new ProjectSoftwareManager("Godoy Cruz", "Latin America"));

Region brazil = new Region("Brazil"); brazil.add(new ProjectSoftwareManager("Carlos da Silva", "Brazil")); brazil.add(new ProjectSoftwareManager("Ronaldo Souza", "Brazil"));

// here the region brazil will be under the region latinamerica latinamerica.add(brazil);

ProjectSoftwareManager psm = new ProjectSoftwareManager("Maximus Vanderbilt", "Rest of the World");

corporation.add(usa); corporation.add(latinamerica); corporation.add(psm); corporation.print; } }

class Google extends SoftwareDeveloper { private ArrayList softwareDeveloper = new ArrayList;

public Google { }

public void add(SoftwareDeveloper c) { softwareDeveloper.add(c); }

public void print { Iterator iterator = softwareDeveloper.iterator;

while (iterator.hasNext) { SoftwareDeveloper c = (SoftwareDeveloper) iterator.next; c.print; } } }

abstract class SoftwareDeveloper { public String getName { return ""; }

public void add(SoftwareDeveloper c) { }

public Iterator iterator { return null; }

public void print { } }

class Region extends SoftwareDeveloper { private SoftwareDeveloper[] softwareDeveloper = new SoftwareDeveloper[100]; private int number = 0; private String name;

public Region(String n) { name = n; }

public String getName { return name; }

public void add(SoftwareDeveloper c) { softwareDeveloper[number++] = c; }

public Iterator iterator { return new RegionIterator(softwareDeveloper); }

public void print { Iterator iterator = iterator;

while (iterator.hasNext) { SoftwareDeveloper c = (SoftwareDeveloper) iterator.next; c.print; } } }

class ProjectSoftwareManager extends SoftwareDeveloper { private String name; private String region;

public ProjectSoftwareManager(String n, String d) { name = n;   region = d;  }

public String getName { return name; }

public void print { System.out.println("Name: " + name + " Division: " + region); }

public Iterator iterator { return new PSMIterator(this); } }

class PSMIterator implements Iterator { private ProjectSoftwareManager psm;

public PSMIterator(ProjectSoftwareManager v) { psm = v; }

public ProjectSoftwareManager next { return psm; }

public boolean hasNext { return false; }

public void remove { } }

class RegionIterator implements Iterator { private SoftwareDeveloper[] softwareDeveloper; private int location = 0;

public RegionIterator(SoftwareDeveloper[] c) { softwareDeveloper = c; }

public SoftwareDeveloper next { return softwareDeveloper[location++]; }

public boolean hasNext { if (location < softwareDeveloper.length && softwareDeveloper[location] != null) { return true; } else { return false; } }

public void remove { } }

code **Output 1:**



Iterator Pattern wrap up
The Iterator pattern can be a handy way to loop through a list and maintain the list's state and position. If it is important to keep your position in the list or to get only a smaller search of a group of records, the Iterator might be a useful pattern to implement. If a list needs to have every record processed in turn and the next cannot be processed before the first, then the Iterator can handle the placement of each object in the list and help the code only return the record needed in a sequential fashion.

Template **ITERATOR**  Composite


 * Chapters **