2009-12-08 4 views
1

Iterator 내부 사용에 문제가 있습니다.자바 내부 클래스 반복자 문제

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

을하지만 그것은 작동하지 않습니다

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 (List<? extends HasWord> sent : sentences) { 
     for (HasWord token : sent) { 
      //do stuff 
     } 
     } 

그래서 내가 청소기 것 인 Iterator을 결정했다. 이 과잉 공격입니까, 아니면 다른 방법으로 할 수 있습니까?

답변

5

가이 작업을 수행하는 두 개의 중첩 for 루프를 가진 근본적으로 아무 문제가 없지만 나는이 깨끗하다고 ​​생각 :

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 
} 

반환이 클래스의 새로운 인스턴스를 여러 문장의 반복자를 필요로 할 때마다, 그리고 (더 신중하게 질문을 읽고 편집) sentences.iterator();

를 사용하여 sentences 필드를 초기화

+0

N 문장이 비어있을 수있는 경우 추가 검사를해야 할 수도 있습니다. – Jorn

3
private class Words implements Iterator<String>, Iterable<String> { 
    ... 
    public Iterator<String> iterator() { 
    return this; 
    } 
    ... 
}