Domanda

Sto avendo difficoltà ad usare un Iterator interno.

private List<List<? extends HasWord>> sentences = new ArrayList<List<? extends HasWord>>(); 
private Iterator<String> wordIterator = new Words();
private class Words implements Iterator<String> {

    int currSentence = 0;
    int currWord = 0;

    @Override
    public boolean hasNext() {
        return currSentence != sentences.size() - 1 && currWord != sentences.get(currSentence).size() - 1;
    }

    @Override
    public String next() {
        String nextWord = sentences.get(currSentence).get(currWord).word();
        currSentence++;
        currWord++;

        return nextWord;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();          
    }

}

Quindi, cerco di scorrere su di esso:

for (String s : wordIterator) { //Error: Can only iterate over an array or an instance of java.lang.Iterable
            words.add(s);

Ma non funziona. (Vedere errore del compilatore commentato la linea di problematica). Che cosa sto facendo male qui?

Su una nota di ingegneria, fare è il modo giusto per risolvere il mio problema? Ho un sacco di cicli di questa forma:

    for (List<? extends HasWord> sent : sentences) {
        for (HasWord token : sent) {
            //do stuff
        }
        }

Così ho deciso di Iterator sarebbe più pulito. È questo eccessivo, o c'è un altro modo lo faresti?

È stato utile?

Soluzione

Non c'è niente di fondamentalmente sbagliato con avere due for nested loop per fare questo, ma penso che questo sarebbe stato più pulito:

public class Words implements Iterator<String> {
  private final Iterator<HasWord> sentences;
  private Iterator<String> currentSentence;

  public boolean hasNext() {
    return currentSentence.hasNext() || sentences.hasNext();
  }

  public String next() {
    if (currentSentence.hasNext()) {
      return currentSentence.next();
    }
    currentSentence = sentences.next();
    return next(); // will return the first word of the next sentence
  }
  //remove() omitted for brevity
}

Restituisce una nuova istanza di questa classe ogni volta che è necessario un iteratore su diverse frasi, e inizializzare il campo sentences utilizzando sentences.iterator();

(A cura dopo aver letto la tua domanda con più attenzione)

Altri suggerimenti

private class Words implements Iterator<String>, Iterable<String> {
  ...
  public Iterator<String> iterator() {
    return this;
  }
  ...
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top