Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Design Patterns Iterator in Java

See this article the concepts, operation and practical implementation of the Iterator design patterns in Java programming language.

Introduction

The Design Patterns are solutions already found, tried and tested and we can apply to projects without having to reinvent the wheel. Various Design Patterns have been cataloged and are a set of best practices that we follow and use in projects of object-oriented software.

Design Patterns basically describe solutions to recurring problems in developing systems of object-oriented software. A design pattern provides a name and define the problem, the solution, when to apply this solution (context) and its consequences.

Additionally, the Design Standards also define a common vocabulary that facilitates communication, documentation and learning software systems.

The design patterns are classified as:

  • Creational - defining the creation of objects;
  • Structural - define the composition of classes and objects;
  • Behavioral - define the interaction between classes and objects.

In this article we will see on the Iterator design pattern that is used in several projects and the Java API.

Operation

The Iterator Pattern Project aims to encapsulate an iteration. The Iterator design pattern depends on an interface called Iterator, as can be seen below:

Example of Iterator Interface

Figure 1: Example of Iterator Interface

The method hasNext () determines whether there are more elements to be iterated. The next () method returns the next object in the iteration.

After that we already have the interface can implement iterators for any collection of objects are arrays, lists, hashtables, etc.. For each collection of objects you want to encapsulate the iteration creates an implementation for the Iterator interface defined above. For example to encapsulate an iteration for a menu would have the class below:

Example Implementation of Iterator Interface

Figure 2: Example Implementation of Iterator Interface

One method that could be part of our diagram is the "remove" to remove objects from the collection, however, this is an optional method, we need not necessarily provide resources for removal.

The Iterator pattern is defined as: "The Iterator pattern provides a way to sequentially access the elements of an aggregate object without exposing its underlying representation." Therefore, we have the standard Iterator allows one access an elements of an array without knowing how they are being represented, so it becomes irrelevant whether the collection of objects is an ArrayList, HashTable or whatever. In addition, the Standard Iterator takes responsibility to access the elements sequentially and transferred this task to the iterator object, so the object aggregator has its simplified interface and implementation and are no longer responsible for iteration.

Implementation Example

Below is an example implementation in Java using the Iterator pattern.

Listing 1: Example of implementation of the Iterator Pattern

class MenuItem {
 
    String nome;
     
    MenuItem(String nome) {
        this.nome = nome;
    }
     
}
 
interface Iterator {
    boolean hasNext();
    Object next();
}
 
public class MenuIterator implements Iterator {
 
    MenuItem[] itens;
    int posicao = 0;
     
    public MenuIterator(MenuItem[] itens) {
        this.itens = itens;
    }
     
    public Object next() {
        MenuItem menuItem = itens[posicao];
        posicao++;
        return menuItem;
    }
     
    public boolean hasNext() {
        if (posicao >= itens.length || itens[posicao] == null) {
            return false;
        } else {
            return true;
        }
    }
     
}

In the example above we have the main class MenuItem that is simply an item from a menu that has a name, this could be a menu that would appear in the menu section of a site, for example.

Below is the interface "Iterator" which is implemented by the class "MenuIterator" who will be responsible for iterating through collection of menus that will be in some sort of collection of objects as an array or an ArrayList. An interesting situation to think about the usefulness of this standard is in the situation where, for example, if we had a class that creates a collection of menus and then we would need to go through this menu to display everything in this collection, how would you implement without using the Iterator interface and class MenuIterator above? Below is a possible solution would solve this problem as:

Listing 2: Example of iterating over menus

public class ShowMenu {
    public static void main(String args []) {
        MenuItem [] menuItens = new MenuItem[4];
         
        menuItens[0] = new MenuItem("Menu 1");
        menuItens[1] = new MenuItem("Menu 2");
        menuItens[2] = new MenuItem("Menu 3");
        menuItens[3] = new MenuItem("Menu 4");
         
        for (int i=0; i < menuItens.length; i++) {
            System.out.println(menuItens[i].nome);
        }
         
    }
}


In the example above we can see that the iteration is all visible in the middle of class, and if we had this iteration into several classes and now we would need to change it, because the type of collection also has changed? What if you were a HashMap menu and not an array? We would have to change too iteration. One can imagine that this would work.

So we created previously Iterator interface and implementation class for MenuIterator Menus. Below is a possible use of the standard Iterator to traverse a collection of objects menu:

Listing 3: Example of iterating over menus using the standard Iterator

public class ShowMenu {
    public static void main(String args []) {
        MenuItem [] menuItens = new MenuItem[4];
         
        menuItens[0] = new MenuItem("Menu 1");
        menuItens[1] = new MenuItem("Menu 2");
        menuItens[2] = new MenuItem("Menu 3");
        menuItens[3] = new MenuItem("Menu 4");
         
        Iterator menuIterator = new MenuIterator(menuItens);
         
        while (menuIterator.hasNext()) {
            MenuItem menuItem = (MenuItem)menuIterator.next();
            System.out.println(menuItem.nome);
        }
    }
}

We may note that the entire internal structure of the iterator pattern was abstracted by Project Iterator getting a much more clean and clear. The only thing we use are the methods next () and hasNext ().

Advantages of the Iterator Pattern

The Iterator Pattern encapsulates implementations of iterations, from now on we no longer need to see what kind of collection is being used by objects such as an ArrayList or HashTable. Using the standard Iterator just need a loop to deal polymorphically with any collection of items since it only implements the Iterator. Previously we were also linked with the code to classes such as ArrayList, now use only one interface (Iterator), remember to always program to interfaces.

Conclusion

The Iterator pattern allows sequential access to elements of an aggregate without exposing its underlying implementation. The Iterator pattern is also responsible for the entire task iteration, thereby removing the added responsibility, thereby simplifying the interface and its implementation leaving the responsibility where it should be. Finally, the standard Iterator refers us to two principles of good projects that are of high cohesion in classes designed around a set of functions related to each other and the Single Responsibility, where the class has a single purpose or responsibility. Although cohesion have a more generic concept, it is closely related to the concept of Single Responsibility.



Higor Medeiros (higorowen@gmail.com) is a student at the University of Vale do Rio dos Sinos in Computer Science studying in 4th semester, where she also works in scientific research in the area of ​​artificial intelli...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login