インナー使いに困っていIterator
ます。
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();
}
}
次に、それを反復しようとします。
for (String s : wordIterator) { //Error: Can only iterate over an array or an instance of java.lang.Iterable
words.add(s);
しかし、うまくいきません。(問題のある行のコメント付きコンパイラ エラーを参照してください)。ここで何が間違っていますか?
エンジニアリングの観点から、私の問題を解決する正しい方法はありますか? この形式のループがたくさんあります。
for (List<? extends HasWord> sent : sentences) {
for (HasWord token : sent) {
//do stuff
}
}
だから私はIterator
よりきれいになると決めました。これはやり過ぎですか、それとも別の方法がありますか?