loading...

Design Patterns - Basic Iterator

achimoraites profile image Achilles Moraites Updated on ・2 min read

Among the most common things in a collection of items is the ability to iterate through the collection.

In Java for example there are data structures that are allowing us to create collections for primitive data or our custom classes.

Here are some : ArrayList<T>, LinkedList<T> , HashSet<T> and others...

The above have something in common , all are implementing the Interfaces : Collection and Iterable.

This can give us the abillity to make our own classes iterable :)

In this article we will explore how to do it.

How it works

Below there is a simplified UML diagram illustrating the ArrayList :

Alt Text

The above relationships are allowing us to use this magic:

for(String s: stringList){
     // do something with s
      System.out.print(s);
}

The above is a convenient way to write a foreach loop in Java, but the language it self translates it to:

Iterator<String> si = stringList.iterator();

while(si.hasNext()){
   String s = si.getNext();
   // do something with s
    System.out.print(s);
}

Now armed with this knowledge we can go beyond the default behaviors of the build in collections and can customize it for our own needs!

Lets play with a project!

Project : CarPartsStore

get the source code here

Here we will illustrate the customized behavior by exploring a Store that sells car parts, in this code-base we have the Warehouse class that contains a List of CarPart .

What we do here: We will use the basic Iterator Pattern to iterate through our Warehouse class for CarPart .

We will make something like the following to work:

for(CarPart part: Warehouse){
  // do interesting stuff ...
}

by default the above is not working as our warehouse has a field of ArrayList , but having the new awesome Iterator powers we can can do it !

in our Warehouse class we have:

public class Warehouse implements Iterable<CarPart> {
  private List<CarPart> carPartList;
  private String location;
...

In our Warehouse class we add the implements Iterable :

public class Warehouse implements Iterable<CarPart> 

notice that we used the CarPart type , as we want to iterate through a collection of CarPart.

also we will implement the following in our Warehouse class :

@Override 
public Iterator<CarPart> iterator() {
    return carPartList.iterator();
}

Now when we try to iterate through our warehouse we iterate through the carPartList !

// Now this magic is available :)
for(CarPart part: Warehouse){
  // do interesting stuff ...
}

Congratulations ! now you have learned how to take iteration to your hands!

Feel free to experiment with the code!!!

Happy coding!!!

the original article was posted here

Posted on by:

achimoraites profile

Achilles Moraites

@achimoraites

Specializing in converting coffee and ideas to code :)

Discussion

pic
Editor guide