java – How to override Iterator's remove() method?

Question:

I created a repository ( RepositorioObjeto ) and it implements the Iterator interface on the object that the repository stores ( Iterator<Objeto> ). So I had to override the next() , hasNext() and remove() methods. I had to adapt the next() , as it only returns the object (that is, it doesn't increment it, I left that for another method because there were some methods that needed to give two next() in the same iteration, causing it to move to another object). Here's 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 I don't know about remove() , what should be implemented? Because the removal method [ removerVendedor ] of the object (which is of type Vendedor ), which follows below, I want to use the remove() that comes with the Iterator , so much so that I call in the method removerVendedor , but for that you have to implement, but how, without code redundancy (code repetition)?

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() {  
}

Answer:

In my view it would be:

@Override
public void remove() {  
      if(posicao <= 0) {
            throw new IllegalStateException("elementos indisponiveis!");
        }
        this.vendedores.remove(--posicao);
}
Scroll to Top