如何避免ConcurrentModificationException 异常

并发修改异常ConcurrentModificationException详解 目录 一、简介 二、异常原因分析 三、异常原因追踪 五、如何避免并发修改异常? 六、总结 一、简介 在多线程编程中,相信很多小伙伴都遇到过并发修改异常ConcurrentModificationException,本篇文章我们就来讲解并发修改异常的现象以及分析一下它是如何产生的。 异常产生原因:并发修改异常指的是在并发环境下,当方法检测到对象的并发修改,但不允许这种修改时,抛出该异常。 下面看一个示例: public class TestConcurrentModifyException 阅读详情
Java Collection classes are fail-fast which means that if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next() will throw a  ConcurrentModificationException .

This situation can come in case of multithreaded as well as single threaded environment.

Lets explore this scenario with the following example:

import java.util.*;
 
public class IteratorExample {
 
    public static void main(String args[]){
        List<String> myList = new ArrayList<String>();
 
        myList.add("1");
        myList.add("2");
        myList.add("3");
        myList.add("4");
        myList.add("5");
 
        Iterator<String> it = myList.iterator();
        while(it.hasNext()){
            String value = it.next();
            System.out.println("List Value:"+value);
            if(value.equals("3")) myList.remove(value);
        }
 
        Map<String,String> myMap = new HashMap<String,String>();
        myMap.put("1", "1");
        myMap.put("2", "2");
        myMap.put("3", "3");
 
        Iterator<String> it1 = myMap.keySet().iterator();
        while(it1.hasNext()){
            String key = it1.next();
            System.out.println("Map Value:"+myMap.get(key));
            if(key.equals("2")){
                myMap.put("1","4");
                //myMap.put("4", "4");
            }
        }
 
    }
}

Output is:
List Value:1
List Value:2
List Value:3
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
    at java.util.AbstractList$Itr.next(AbstractList.java:343)
    at com.journaldev.java.IteratorExample.main(IteratorExample.java:27)

From the output stack trace, its clear that the exception is coming when we call iterator next() function. If you are wondering how Iterator checks for the modification, its implementation is present in AbstractList class where an int variable modCount is defined that provides the number of times list size has been changed. This value is used in every next() call to check for any modifications in a function checkForComodification().

Now comment the list part and run the program again.

Output will be:

Map Value:3
Map Value:2
Map Value:4

Since we are updating the existing key value in the myMap, its size has not been changed and we are not getting ConcurrentModificationException. Note that the output may differ in your system because HashMap keyset is not ordered like list. If you will uncomment the statement where I am adding a new key-value in the HashMap, it will cause ConcurrentModificationException.

To Avoid ConcurrentModificationException in multi-threaded environment:

1. You can convert the list to an array and then iterate on the array. This approach works well for small or medium size list but if the list is large then it will affect the performance a lot.

2. You can lock the list while iterating by putting it in a synchronized block. This approach is not recommended because it will cease the benefits of multithreading.

3. If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach.

To Avoid ConcurrentModificationException in single-threaded environment:

You can use the iterator remove() function to remove the object from underlying collection object. But in this case you can remove the same object and not any other object from the list.

Let us run an example using Concurrent Collection classes:

package com.journaldev.java;
 
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
 
public class ThreadSafeIteratorExample {
 
    public static void main(String[] args) {
 
        List<String> myList = new CopyOnWriteArrayList<String>();
 
        myList.add("1");
        myList.add("2");
        myList.add("3");
        myList.add("4");
        myList.add("5");
 
        Iterator<String> it = myList.iterator();
        while(it.hasNext()){
            String value = it.next();
            System.out.println("List Value:"+value);
            if(value.equals("3")){
                myList.remove("4");
                myList.add("6");
                myList.add("7");
            }
        }
        System.out.println("List Size:"+myList.size());
 
        Map<String,String> myMap = 
             new ConcurrentHashMap<String,String>();
        myMap.put("1", "1");
        myMap.put("2", "2");
        myMap.put("3", "3");
 
        Iterator<String> it1 = myMap.keySet().iterator();
        while(it1.hasNext()){
            String key = it1.next();
            System.out.println("Map Value:"+myMap.get(key));
            if(key.equals("1")){
                myMap.remove("3");
                myMap.put("4", "4");
                myMap.put("5", "5");
            }
        }
 
        System.out.println("Map Size:"+myMap.size());
    }
 
}
Output is:
List Value:1
List Value:2
List Value:3
List Value:4
List Value:5
List Size:6
Map Value:1
Map Value:null
Map Value:4
Map Value:2
Map Size:4

From the above example its clear that:

1. Concurrent Collection classes can be modified avoiding ConcurrentModificationException.

2. In case of CopyOnWriteArrayList, iterator doesn’t accomodate the changes in the list and works on the original list.

3. In case of ConcurrentHashMap, the behavior is not always the same.

For condition:

if(key.equals("1")){
    myMap.remove("3");

Output is:
Map Value:1
Map Value:null
Map Value:4
Map Value:2
Map Size:4

It is taking the new object added with key “4? but not the next added object with key “5?.

Now if I change the condition to

if(key.equals("3")){
    myMap.remove("2");
Output is:
Map Value:1
Map Value:3
Map Value:null
Map Size:4

In this case its not considering the new added objects.

So if you are using ConcurrentHashMap then avoid adding new objects as it can be processed depending on the keyset. Note that the same program can print different values in your system because HashMap keyset is not in any order.

Extra Toppings:

for(int i = 0; i<myList.size(); i++){
    System.out.println(myList.get(i));
    if(myList.get(i).equals("3")){
        myList.remove(i);
        i--;
        myList.add("6");
    }
}

If you are working on single-threaded environment and want your code to take care of the extra added objects in the list then you can do so using following code and avoiding iterator.

Note that I am decreasing the counter because I am removing the same object, if you have to remove the next or further far object then you don’t need to decrease the counter.

Try it yourself.

Reference :  http://www.javacodegeeks.com/2011/05/avoid-concurrentmodificationexception.html

http://www.oschina.net/code/snippet_12_4199

微信小程序-如何根据缩放屏幕大小自适应icon图标更改marker 微信小程序如何根据用户的缩放屏幕来改变marker图标icon的大小,实现icon自适应屏幕缩放的效果 阅读详情

相关推荐

AI辅助专利撰写实战:用Codex 30分钟生成发明专利初稿

这次我们来看一个用 Codex 从零开始撰写发明专利的实战项目。对于技术研发人员、产品经理或初创团队来说,专利申请是保护创新成果、构建技术壁垒的关键一步。然而,撰写一份高质量的专利申请书,尤其是权利要求书和说明书,往往需要专业的法律和技术语言,耗时耗力。这个项目演示了如何利用 AI 工具 Codex,在短时间内生成一份结构完整、逻辑清晰、具备授权潜力的专利申请文件初稿。 整个过程的核心不是让 AI 完全替代专利代理人,而是将其作为强大的“技术翻译”和“内容生成”助手。它能将你的技术构思、流程图、核心算法或产

weixin_32181267的博客 415

如何避免 ConcurrentModificationException 异常

在实际生产过程中,碰到了一个概念中的异常,ConcurrentModificationException。 这个异常主要出现在集合的遍历中,对集合进行了add或者remove的操作; 以ArrayList为例子,当在forEach的时候,对list本身进行add或者remove的操作,查看ArrayList的源码,相当于是移动了指针;点击查看 以HashMap为例,集合的修改有一个modCount...

张小挑的博客 1919

拯救者R9000P-2021-AMD5800H黑苹果EFI配置与优化指南

本文详细介绍了在联想拯救者R9000P 2021款(搭载AMD锐龙7 5800H处理器)上安装和优化黑苹果系统的完整指南。内容涵盖EFI配置、OpenCore引导设置、关键驱动(如NootedRed核显驱动)的调整,以及安装后的性能调优与常见问题解决,旨在帮助开发者和极客用户在这款游戏本上搭建稳定可用的macOS开发环境。

weixin_29291069的博客 289

如何避免ConcurrentModificationException

ConcurrentModificationException出现原因: 1.在Java集合类中,当我们在使用iterator遍历集合对象时,当集合被改变且在使用迭代器遍历集合的时候,迭代器的next()方法将抛出ConcurrentModificationException异常。 2.如果subList()生成一个新的List对象,那么当修改原始List对象的结构时,则将抛出ConcurrentModificationException import java.util.ArrayList; import

weixin_43664019的博客 585

ESP32内存优化实战:关闭WiFi/LWIP功能释放37KB IRAM的隐藏技巧

本文针对ESP32开发中IRAM内存不足的难题,提供了一种通过关闭WiFi和LWIP协议栈的IRAM优化功能来释放宝贵内存空间的实战技巧。该方法最高可释放约37KB的IRAM,有效解决复杂项目(如WiFi+BLE+语音识别)的编译失败问题,并详细阐述了配置步骤、性能权衡与测试验证方法。

redis7keeper的博客 131

UVM自学笔记3——项目之三——从零开始搭建ahb_sramc验证平台

创建如下所示的目录结构: 2.在tb的文件下:顶层的testbench如下:在tb中,第24行的代码将uvm宏相关的内容include进来,第26行的代码把uvm_pkg包导入进来,然后将agent相关的包(ahb_pkg/sram_pkg),testcase相关的包(uvm_ahb_sram_test_pkg)以及env相关的包(uvm_ahb_sram_env_pkg)都导入进来,在第38行和39行将接口以virtual interface的形式配置给ahb_agent和sramc_agent下

ZhangShuHuai11的博客 9477

4.ConcurrentModifyException的产生原因及如何避免

4.ConcurrentModifyException的产生原因及如何避免目录1 关于ConcurrentModificationException2 单线程触发场景举例  2.1 单线程触发举例  2.2 解决单线程环境的ConcurrentModificationException异常  2.3 ArrayList集合改为CopyOnWriteArrayLis  2.4 通过迭代器遍历删除  ...

大屎蛋教程网 8007

[ vulhub漏洞复现篇 ] Django SQL注入漏洞复现 CVE-2021-35042

[ vulhub漏洞复现篇 ] Django SQL注入漏洞复现 CVE-2021-35042 Django 组件存在 SQL 注入漏洞,该漏洞是由于对 QuerySet.order_by()中用户提供数据的过滤不足,攻击者可利用该漏洞在未授权的情况下,构造恶意数据执行 SQL 注入攻击,最终造成服务器敏感信息泄露。

qq_51577576的博客 3228

ConcurrentModificationException 避免

背景: 在网络程序中经常遇到多个线程同时去操作一个集合Set,List.Map,Queue。Hashtable,Vector 在迭代集合的时候如何避免java.util.ConcurrentModificationException的发生。 以Hashtable为例,api中不是说Hashtable是同步的吗? 答:通过源码查看Hashtable中有一个keySet内部类,keySet对象又

javaee_ssh的专栏 7156

如何正确的计算两个角度的角度差?

这一步是必要的,因为它确保了无论a相对于b是在逆时针方向还是顺时针方向,d2总是正确地反映出绕圆相反方向的角度差。这样,当函数进行最后的比较时,它能够准确地比较两个方向的旋转路径并选择最短的一个。

小秋 AI SLAM 入门实战教程 4137

GEE:计算非水体概率影像(水体淹没次数)

本文记录了在GEE平台上使用哨兵数据计算沿海地区非水体概率图像的计算方法和代码。基于像素,概率范围0-100。首先使用哨兵数据(s2)和大津算法(OTSU)计算的水体指数阈值来提取水体,然后计算研究区非水体像素在时间段内出现的概率。

养乐多的博客 2141

ConcurrentModificationException 并发修改异常的出现原因以及避免方法?

并发修改异常 (ConcurrentModificationException)出现原因: 在使用迭代器遍历集合的同时,使用集合对象增加集合的元素;迭代器是依赖集合而存在的,在判断成功后,集合中新增加了元素,而迭代器却不知道就报错了。 /** * 迭代器遍历 + 集合添加 * @param data */ public static void mixture(List<Integer> data) { for(Integer number : data) {

xuewei_ing的博客 699

IEEE Journal of Biomedical and Health Informatics(JBHI)投稿经验分享

《IEEE Journal of Biomedical and Health Informatics投稿经验分享》详细记录了在影响因子6.7的中科院一区期刊JBHI的投稿历程(2025.1-5月,历时4个月)。文章重点分析:1)审稿特色:4位审稿人差异显著,领域专家意见专业但要求严苛;2)修改要点:需重视大修(补充实验/原理阐述),并注意将回复内容同步至正文;3)期刊特点:送审率高但审稿严格,常规投稿周期约4-5个月;4)实用建议:建议首次大修全力以赴,善用AI工具辅助写作,避免拖延。

LiRongLu_的博客 5089

java遍历集合时移除元素,怎样避免ConcurrentModificationException异常抛出

Java 必知必会 第 53 篇 遍历集合时移除元素,怎样避免ConcurrentModificationException异常抛出 问题: 在遍历集合的过程中,不会总出现ConcurrentModificationException异常的抛出,但是在下面的代码块中: public static void main(String[] args) { Collection<Intege...

十年互联网开发老兵,陪你一起学技术 643

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

避免低级错误:深入解析Java的ConcurrentModificationException异常

作为开发者,避免低级错误同样重要。希望本文能帮助读者更好地理解并解决异常,以及在开发中提高代码质量,减少不必要的问题发生。同时,重视测试工作,让我们的项目在实际应用中更加稳定和可靠。

修己xj的博客 535

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

List集合删除元素方式:避免java.util.ConcurrentModificationException异常

方式一,使用Iterator,顺序向下,如果找到元素,则使用remove方法进行移除。方式二,倒序遍历List,如果找到元素,则使用remove方法进行移除。方式三,正序遍历List,如果找到元素,则使用remove方法进行移除,然后进行索引“自减”。方式四,使用jdk1.8新增的Stream流操作。...

*** 棋了个怪_Rachel *** 2175

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

ConcurrentModificationException异常

一:ConcurrentModificationException异常: 当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常。 二:遍历list集合时删除元素出现的异常 public static void main(String[] args) { ArrayList&lt;String&gt; list=new ArrayList&lt;String&gt;(); ...

小礼貌的博客 9万+

ConcurrentModificationException异常原理及有关处理

ConcurrentModificationException异常原理及有关处理

qq_46027570的博客 689

关于list的ConcurrentModificationException 异常

此类在源码中的注解为: /** * An {@code ConcurrentModificationException} is thrown when a Collection is * modified and an existing iterator on the Collection is used to modify the * Collection as well. */

999

java.util.ConcurrentModificationException异常处理

测试程序时,报java.util.ConcurrentModificationException异常。google后发现,是由于Iterator表示的哈希表变化造成的,代码如下: Iterator> iterator = hash.entrySet(); while (iterator.hasNext()) { ...... }在执行过程中,其他部分执行了hash.put或hash.remo

Nonetracer的专栏 891

Java ConcurrentModificationException 异常分析与解决方案

一、单线程 1. 异常情况举例     只要抛出出现异常,可以肯定的是代码一定有错误的地方。先来看看都有哪些情况会出现ConcurrentModificationException异常,下面以ArrayList remove 操作进行举例: 使用的数据集合: List myList = new ArrayList(); myList.add

Android 3万+

关于ConcurrentModificationException异常

在使用增强 for 循环遍历ArrayList,同时删除某元素时,遇到ConcurrentModificationException异常 for(Person p : personList) { if(id.equals(p.getId)) { personList.remove(p); } } 因为使用增强for循环的时候,内部原理是调...

weixin_30346033的博客 99

LinkedList 跑出的ConcurrentModificationException异常

LinkedList后台抛出了ConcurrentModificationException异常

smithdoudou88的专栏 3446

java.util.ConcurrentModificationException异常原因及解决方法

通过错误提示,知道了异常出现在checkForComodification这个方法上,异常原因是modCount!在网上查询得知,在很多容器中,都有一个变量记录你从结构上修改此容器的次数,叫做modCount,查看ArrayList的add()和remove()方法就可以发现,每次你调用add方法()向容器里面增加了一个元素,或者你调用Remove()方法删除了其中的某个元素,这个值都会增加1。

LYQ 6719

Java 遍历List ConcurrentModificationException 异常解析

ConcurrentModificationException 异常解析

益达还有么的博客 1万+

【小家java】Java中集合List、Set、Map删除元素的方法大总结(避免ConcurrentModificationException异常)

1、概述 java中的集合框架是我们日常使用得最多的数据结构,而List作为Collection里最重要的一员,使用就更加的频繁了。因此我们平时使用中少不了对List的增删改查,本文就针对于对List的“删”操作进行一个分析,顺便说几个坑,希望能帮助到大家以后可以避免踩坑 2、栗子 有一个List,如果我们要删除其中的一个元素,怎么办呢? 这里我们先用remove方法 3、使用场景...

架构师:通透,才能写出好代码! 2825
上一篇: android系统信息(内存、cpu、sd卡、电量、版本)获取
下一篇: 多条Notification更新,保持位置不变
nevercool
博客等级 码龄20年 4粉丝 2原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值