如何解决为什么在使用listIterator.add时出现noSuchElementException?
在没有进一步延迟的情况下,我将立即发布我的代码。这非常简单,因此您在理解它时不会发现任何问题。我的想法是在使用add
找到“蓝色” 后,listIterator
颜色。显然这里有问题。
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)
解决方法
您有2次hasNext()
呼叫一次next()
。调用一次并保存即可使用
while (iterator.hasNext()){
Color current = iterator.next();
System.out.println(current);
if (current.tone.equals("blue")){
iterator.add(new Color("yellow"));
}
}
,
我知道提供了答案,但如果有帮助则发布 请参阅以下代码:-
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();
System.out.println(iterator.next());//-->red
System.out.println(iterator.next());//-->blue
System.out.println(iterator.next());//-->green
System.out.println(iterator.next());//-->java.util.NoSuchElementException (iterator is moved forward but list is exhausted)
}
因此基本上iterator.next()
在可迭代集合中定位元素。
因此,在您的iterator.next()
循环中多次调用while
会将游标的传送时间移至下一个值,因此最好将iterator.next()
存储到循环内的变量中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。