java - 打印 vector 内容时出现 ConcurrentModificationException

标签 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)

第 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");
}
}

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

最佳答案

在向 Vector 添加任何内容之前,您过早地创建了迭代器。移动这一行:

Iterator<Integer> itr = v.iterator();

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

Iterator<Integer> itr = v.iterator();
while(itr.hasNext()){

...在你修改完Vector之后。

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

关于java - 打印 vector 内容时出现 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17197960/

相关文章:

带有迭代器的 java.util.ConcurrentModificationException

java - Collections.synchronized 映射是否使 Iterator 线程安全

java - 同时从 ArrayList 中删除两个对象而不引发 ConcurrentModificationException?

使用集合删除方法时不会出现 Java 并发修改异常

java - Android 使用 Jsoup 解析多个 HTML 表

java - 使用private指定类的访问控制

java - 解析 JSON 数据时出错 - 异步任务

java - 绘画导致并发修改异常?

java - 客户端可以同时向多个服务器发送消息吗?

Java 和 SWIG : class into a package