LinkedList Iterator next()抛出NoSuchElementException,即使在hasNext()返回true后调用也是如此

时间:2013-06-21 11:32:43

标签: java linked-list nosuchelementexception

LinkedList Iterator next()即使在hasNext()返回true后调用,也会抛出NoSuchElementException。

环境:Sun Solaris上的Java 6

我知道为什么我在next()方法调用上遇到这个异常?

// lines is an instance of LinkedList
// writer is a FileWriter, Believe that is irrelevant to issue
while(lines.hasNext()){
    int i = 0;
    do {
            writer.write(lines.next());
            writer.newLine();
            i++;
    } while (lines.hasNext() && i < targetLineCount);
    // Some more code... 
}

使用更多代码进行更新

public class MyClass { // Only one instance of this class is used across application
    private List<String> master = new LinkedList<String>();
    // Other instance members to tune this instance behaviour

    public MyClass(){
        // Read Source & populate master
    }

    public boolean writeDataSlot(Writer writer, int targetLineCount){ // Can be called by different Threads
        Ierator<String> lines = master.iterator();
        while(lines.hasNext()){
            int i = 0;
            do {
                writer.write(lines.next());
                writer.newLine();
                i++;
            } while (lines.hasNext() && i < targetLineCount);
            // Some more code to populate slot from different source.
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我看到了这些可能性:

  1. lines用于其他线程
  2. lines.next() 中调用
  3. // some more code...
  4. lines绑定到// some more code...
  5. 中的另一个实例

答案 1 :(得分:0)

正如Axel指出的那样,似乎就像一个线程问题。

如果您使用此方法synchronized会怎样?

public synchronized boolean writeDataSlot(Writer writer, int targetLineCount)