Design Patterns Java - Iterator Php

1) What have we done?

We implemented a java interface "Iterable" and create an inner class which implements an "Iterator" interface.


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;

public class Collection implements Iterable<String>
{
    private List<String> elements = new ArrayList<>();

    public Collection addElement(String element)
    {
        elements.add(element);

        return this;
    }

    public Collection removeElement(String element)
    {
        elements.remove(element);

        return this;
    }

    @Override
    public Iterator<String> iterator()
    {
        return new CollectionIterator();
    }

    class CollectionIterator implements Iterator<String>
    {
        private int position;

        @Override
        public boolean hasNext()
        {
            return position <= elements.size() - 1;
        }

        @Override
        public String next()
        {
            return elements.get(position++);
        }
    }
}




2) What are pros?

Now we can iterate on "Collection" by enhanced "for" loop without direct accessing the inner structure.


import java.util.Iterator;

public class Client
{
    public static void main(String[] args)
    {
        Collection collection = new Collection();
        collection
                .addElement("a")
                .addElement("b")
                .addElement("c")
                .addElement("d")
                .addElement("e");

        for (String str : collection)
        {
            System.out.println(str);
        }
    }
}