打印向量内容时出现 ConcurrentModificationException

boo*_*y99 3 java concurrentmodification

好吧,我想编写一个程序,允许用户输入无限数量的数字,然后再次以相同的顺序打印它们。

我收到此错误:

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)
Run Code Online (Sandbox Code Playgroud)

第 41 行是这一行“System.out.println(itr.next());” 一

这是我的代码:

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");
}
}
Run Code Online (Sandbox Code Playgroud)

我是否搞砸了迭代器?提前致谢!

rge*_*man 5

您太早创建了迭代器,甚至在向Vector. 移动这一行:

Iterator<Integer> itr = v.iterator();
Run Code Online (Sandbox Code Playgroud)

在最后一个 while 循环中使用它之前:

Iterator<Integer> itr = v.iterator();
while(itr.hasNext()){
Run Code Online (Sandbox Code Playgroud)

...并且在完成修改后Vector。

您看到 a 的原因ConcurrentModificationException是您在存在Vector时修改了 the Iterator。