Reputation: 1456
Ok so I'm wanting to write a program which allows the user to enter an infinite amount of numbers and then they would be printed in the same order again.
I am getting this error:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.Vector$Itr.checkForComodification(Unknown Source)
at java.util.Vector$Itr.next(Unknown Source)
at myPackage.Main.main(Main.java:41)
The 41st line is this line "System.out.println(itr.next());" one
Here is my code:
package myPackage;
import java.util.Scanner;
import java.util.Vector;
import java.lang.Integer;
import java.util.Iterator;
public class Main {
private static Scanner user_input;
public static void main(String[] args) {
int first = 42;
int second = 84;
user_input = new Scanner(System.in);
Vector<Integer> v = new Vector<Integer>();
Iterator<Integer> itr = v.iterator();
System.out.println("Please enter the numbers you wish to store temporarily before printing. When finished, enter either 42 or 84");
int userInt = user_input.nextInt();
while(user_input.equals(first) == false && user_input.equals(second) == false){
userInt = user_input.nextInt();
if(userInt == 42 || userInt == 84){
break;
}
else{
v.add(userInt);
}
}
System.out.println("Iterating through Vector elements...");
while(itr.hasNext()){
System.out.println(itr.next());
}
System.out.println("The program has terminated");
}
}
Did I mess up on the Iterator? Thanks in advance!
Upvotes: 3
Views: 3070
Reputation: 27220
See JavaDoc, bold are mine:
The Iterators returned by Vector's iterator and listIterator methods are fail-fast: if the Vector is structurally modified at any time after the Iterator is created, in any way except through the Iterator's own remove or add methods, the Iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the Iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. The Enumerations returned by Vector's elements method are not fail-fast.
In your case, you modified the vector after the creation, which gave you the exception in the post.
Upvotes: 3
Reputation: 178293
You created your iterator too early, before you even added anything to the Vector
. Move this line:
Iterator<Integer> itr = v.iterator();
to immediately before you use it in the last while loop:
Iterator<Integer> itr = v.iterator();
while(itr.hasNext()){
...and after you have finished modifying the Vector
.
The reason you saw a ConcurrentModificationException
is that you modified the Vector
while the Iterator
existed.
Upvotes: 5