Iterator

Objetivo

Também conhecido como

Motivação

Aplicabilidade

Estrutura

iterator1.gif (6164 bytes)

Exemplo de uso: um impressor genérico em Java

class Printer {
    static void printAll(Iterator it) {
        while(it.hasNext()) {
            System.out.println(it.next().toString());
        }
    }
}

class LabirintoDeRatos { 
    public static void main(String[] args) { 
        Collection <Rato> ratos;
        ratos = new ArrayList <Rato>(); 
        for(int i = 0; i < 3; i++) { 
            ratos.add(new Rato(i)); 
        }
        // iterador criado aqui
        Printer.printAll(ratos.iterator());
    } 
}

Participantes

Conseqüências

Detalhes de implementação

Exemplo de código

public Iterator iterator() {
    return new Iterator() { // classe interna anônima
        int cursor = 0;

        public boolean hasNext() {
            return cursor < size();
        }

        public Object next() {
            try {
                Object next = get(cursor);
                cursor++;
                return next;
            } catch(IndexOutOfBoundsException e) {
                throw new NoSuchElementException();
            }
        }
    };
}

Perguntas finais para discussão

programa