gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:36:45 25 4
gpt4 key购买 nike

即使在 hasNext() 返回 true 后调用,LinkedList 迭代器 next() 也会抛出 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.
}
}
}

最佳答案

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

如果将此方法同步会发生什么?

public synchronized boolean writeDataSlot(Writer writer, int targetLineCount)

关于java - 即使在 hasNext() 返回 true 后调用,LinkedList Iterator next() 也会抛出 NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17234223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com