不再拖延,我将立即发布我的代码。它非常简单,所以理解它应该不会有任何问题。我的想法是使用 listIterator
找到 "blue" 后添加
颜色。显然这里有问题。
public class Main {
public static void main(String[] args) {
Color c1 = new Color("red");
Color c2 = new Color("blue");
Color c3 = new Color("green");
List<Color> list = new ArrayList<>();
list.add(c1);
list.add(c2);
list.add(c3);
ListIterator<Color> iterator = list.listIterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
if (iterator.next().tone.equals("blue")){
iterator.add(new Color("yellow"));
}
}
}
}
class Color {
String tone;
public Color(String tone) {
this.tone = tone;
}
@Override
public String toString() {
return tone;
}
}
输出:
red
green
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:999)
at Main.main(Main.java:21)
最佳答案
您调用 hasNext()
一次,即可调用 next()
两次。调用一次,保存即可多次使用
while (iterator.hasNext()){
Color current = iterator.next();
System.out.println(current);
if (current.tone.equals("blue")){
iterator.add(new Color("yellow"));
}
}
关于java - 为什么在使用 listIterator.add() 时出现 noSuchElementException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64092798/