How to override the Iterator remove () method?

3

I created a repository ( RepositorioObjeto ) and it implements the Iterator interface on the object that the repository stores ( Iterator<Objeto> ). So I had to overwrite the methods next() , hasNext() and remove() . I had to adapt the next() , because it only returns the object (that is, it does not increment it, I left it to another method because it had some methods that needed to give in a same iteration two next() , causing it to move to another object). Here is the code for next() and hasNext() :

public Vendedor next(){
    Vendedor vendedor = this.vendedores.get(posicao);
    return vendedor;
}

public boolean hasNext(){
    boolean temProximo = true;//posto true pois comumente será mais vezes true
    if (posicao >= this.vendedores.size() || this.vendedores.get(posicao) == null) {
        temProximo = false;
        zerarContadorPosicao();
    }
    return temProximo;
}

public static void incrementarContadorPosicao(){
    posicao++;
}

NOTE: Position is a static attribute

The big problem that I do not know how is remove() , what should be implemented? Because the method of removing [ removerVendedor ] from the object (which is of type Vendedor ), which follows immediately below, I want to use the remove() that comes with Iterator , so much that I call in the removerVendedor , but for that it has to be implemented, but how, without any code redundancy?

public void removerVendedor(String cpfVendedor) throws NaoEncontradoVendedorException{
    boolean removeu = false;
    if (!cpfVendedor.equals("") && !cpfVendedor.equals(" ")){
        ListIterator<Vendedor> iVendedor = this.vendedores.listIterator();
        while(iVendedor.hasNext()){
            if (iVendedor.next().getCpf().equals(cpfVendedor)){
                iVendedor.remove();
                removeu = true;
                zerarContadorPosicao();
                salvarArquivo();
                break;
            }
            incrementarContadorPosicao();
        }
    }

    if (removeu == false){
        throw new NaoEncontradoVendedorException();
    }
}

@Override
public void remove() {  
}
    
asked by anonymous 18.06.2015 / 06:16

1 answer

1

In my opinion it would be:

@Override
public void remove() {  
      if(posicao <= 0) {
            throw new IllegalStateException("elementos indisponiveis!");
        }
        this.vendedores.remove(--posicao);
}
    
18.06.2015 / 06:54