Without further delay, I will post my code straight away. It is very simple so you shouldn't find any problems understanding it. My idea is to add color after it found "blue" using listIterator. Apparently there is something wrong here.
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;
}
}
OUTPUT:
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)