关于上个在foreach中ArrayList.Remove出错的解释

C# List Remove 注意事项 项目的GitHub地址   以下代码应该输出什么呢?using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace TestCollectionDelete { class Program { 阅读详情
关于上一篇中在foreach中Remove某一ArrayList的tiem会出错的问题,在网上搜了一下,发现这居然是一个臭名昭著的Collection问题,许多人第一次这样做的时候都中招了,现在将问题出现的原因及解决方法记录一下,确保以后不要再犯这种错误。

首先是foreach:
MSDN中的说明:foreach 语句为数组或对象集合中的每个元素重复一个嵌入语句组。foreach 语句用于循环访问集合以获取所需信息,但 不应用于更改集合内容以避免产生不可预知的副作用。

其次是ArrayList.Remove:
当你remove第i个item时,第[i + 1, count)域中所有items的索引值皆减一(Array是连续的,要满足只要有k ∈ [0, count)则Array[k]必存在),那么当你在循环下一轮用i + 1为索引访问的即是原先list中索引为i + 2的那个item,由此可知,假设0号被删除时,原1号变为新0号,原2号变为新1号。。。下一轮访问的1号就是先前的2号,而原始的1号则永远没有被访问到 。

由上面的总结可以看出,这里出现 InvalidOperationException异常的原因应该是在foreach中更改了Collection集合内容的缘故,而不是我想象中的ArrayList发生了断链,尽管在foreach循环中会少访问一个item。

问题的解决方法有好多种,除了上一篇中我的解决方法外,还可以在foreach里面用Clone,for循环,ToArray……等等多种方法。
这里我选择用反向for循环方法来解决,因为这是几种方法中最高效的。修改上篇的代码为:
         public   void  DeleteOneUser( string  userSIPURI)
        
{
            
for (int i = userArray.Count; --i >= 0; )
            
{
                
if (((PoCContactItem)userArray[i]).GetUserSipUri() == userSIPURI)
                
{
                    userArray.RemoveAt(i);
                }

            }

            RefeshSesonTreVw();
        }
程序运行正常。
反向for循环的方法非常简洁,推荐。


以上内容部分来自 http://blog.csdn.net/i_like_cpp/archive/2005/01/30/273843.aspx  
10万元AI智能体落地实战:SaaS、RPA+Agent与开源自研三路径对比 AI智能体是企业实现业务自动化的重要技术形态,其核心在于将大模型能力与具体任务流程深度结合。原理上,它依赖于任务编排、工具调用与决策闭环三大机制,技术价值体现在降低人力重复操作、提升响应实时性与增强规则执行刚性。典型应用场景包括结构化数据处理(如运单解析)、跨系统流程协同(如HR入职自动化)及非结构化信息理解(如会议纪要生成)。在预算受限的现实条件下,SaaS方案以开箱即用和低运维成本见长,RPA+Agent组合兼顾灵活性与可控性,而开源自研则适用于强定制与高集成需求。本文聚焦10万元级真实项目约束,结合S 阅读详情

相关推荐

Dify与钉钉轻量级集成:打造企业内部AI助手

企业级聊天机器人开发已成为提升内部协同效率的关键技术。其核心原理在于通过API集成,将AI模型能力与即时通讯平台无缝连接,实现智能问答与自动化流程。从技术价值看,这种集成方案能够显著降低AI应用落地门槛,将前沿的AI能力快速转化为实际生产力。在应用场景上,它尤其适用于HR答疑、IT技术支持、产品知识库等高频内部服务场景。本文聚焦于Dify与钉钉的轻量级集成方案,通过Stream模式实现高效消息处理,并利用AI卡片支持流式输出,为企业构建体验自然的智能机器人提供了完整实践路径。该方案特别强调配置简化与部署便捷

weixin_27155667的博客 704

foreach中remove/add报错问题?!

- 问题引入 public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("kobe"); list.add("james"); list.add("curry"); for (String s : list) { if (s.e...

weixin_43872459的博客 803

FreeRTOS --(15)信号量之概述

FreeRTOS 中使用信号量来做同步,信号量可以在任务中使用作为任务与任务间的同步,也可以在中断中使用(带 FromISR 的版本)中断与任务间的同步; 针对不同的应用场景,信号量分为两种: 1、二值信号量; 2、计数信号量; 1、二值信号量 1.1、Usage 顾名思义,二值信号量只有两个值:0 和 1;它用于简单场景下的任务与任务、中断与任务之间的同步,比如:一个任务,在等待某个资源到位后,才能够继续执行,在得到这个资源之前,它处于阻塞状态,假如一个中断来了,给出了这个资源,那么.

StephenZhou 6525

java使用for each或迭代器遍历容器(如List)并执行remove操作时出现错误

java中遍历删除最保险使用迭代器的remove方法,本文删除部分不使用时的错误。

Mechanic_PK的博客 1840

基于STM32+OV7670的图像采集系统(基础篇:ov7670介绍)

一、简单认识 先来看一下外观: OV7670,图像传感器,体积小,工作电压低,提供单片VGA摄像头和影像处理器的所有功能。通过SCCB总线控制,可以输入整帧、子采样、取窗口等方式的各种分辨率8位影像数据。 其他介绍比较繁琐,这里就不一一赘述了,我们只需要知道它是通过SCCB总线控制的就行了。 带FIFO与不带FIFO 目前市场上购买的ov7670模块分为两种,一种是不带FIFO芯片、一种是带FIFO芯片的。 FIFO是什么:(First Input First Output)先入先出的意思,

m0_59113542的博客 4万+

CLIP-Count代码配置以及踩坑记录

CLIP-Count代码配置以及踩坑记录

学术菜鸡 1016

foreach中使用remove问题

先贴代码:     List a = new ArrayList();         a.add("1");         a.add("2");         for (String temp : a) {             if ("2".equals(temp)) {                 a.remove(temp);             }   

ch的博客 6557

基于 Logistic 混沌映射和 Arnold 变换 的变换域水印改进算法【高级网络与信息安全技术-信息隐藏期末课程论文】

摘要:\textbf{摘要:}摘要:本文提出了一种新的水印算法是一种图像认证的新方法。算法首先使用Logistic混沌映射加密水印图像,然后使用Arnold变换置乱水印。同时改变了水印图像的像素位置和像素值,大大提高了算法的安全性。再使用DCT变换嵌入水印,并且结合人类视觉系统的特点来提升水印嵌入的透明性。实验结果表明,本文提出的水印算法可以大幅度提高水印嵌入的透明性与安全性的同时,并不降低算法的鲁棒性。注:完整的代码和论文在文末,百度网盘链接。

zik的博客 897

ArrayList在foreach循环的时候remove元素报错

jdk基于fast-fail机制,当集合内部结构发生预期外变化时抛出ConcurrentModificationException

极客中年的博客 748

面向 Cloud Foundry、ABAP On-Prem 与 ABAP Cloud 的 SAP Fiori 开发全景:工具、流程与实战案例

SAP Fiori开发实战:基于BAS的一站式工程化方法 摘要: 本文系统梳理SAP Business Application Studio(BAS)在Fiori开发中的核心能力,提供三种典型后端(Cloud Foundry/ABAP On-Prem/ABAP Cloud)的对接方案。BAS通过预置Fiori Tools套件、MTA部署工具等扩展,支持从模板创建、可视化建模到构建部署的全流程。文章包含CAP+RAP服务对接、ABAP标准应用扩展等实战案例,重点解析注解驱动开发、Adaptation Proj

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 261

【WRF理论第十九期】内陆湖泊、水体的处理方式

【WRF理论第十九期】内陆湖泊、水体的处理方式

WW、forever的博客 363

是否可以修改数据库超限额警告消息的发件人

是否可以修改数据库超限额警告消息的发件人 环境 产品:Lotus Domino Server平台:无关版本:6.x

点点滴滴 1216

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

java中foreach语句中使用remove时出现的问题

先粘上测试代码:public  class test {    public static void main(String[] args) {       List&lt;Integer&gt; list=new ArrayList&lt;&gt;();       list.add(1);       list.add(2);       list.add(3);       for(Inte...

kongshaohao的博客 1496

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

深度学习工具包 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")

foreach循环遍历List,删除其中某元素报错问题

1. foreach循环遍历List集合,并删除其中的"lisi" public class TestListDel { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("zhangsan"); list.add("simon")...

stormkai的专栏 3871

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

C# Foreach Dictionary.Remove() 报错:集合已修改;可能无法执行枚举操作

C#在对集合进行值修改或者Remove(key)的时候不能使用Foreach,否则Count和索引会在循环的时候更改,可以使用for循环遍历。 int[] keyArray = userSockets.Keys.ToArray<int>(); for (int i = 0; i < keyArray.Length; i++) { if (socket == userSockets[keyArray[i]]) { userSockets.Remove(ke

AdamShyly的博客 1726

Java关于foreach循环remove/add元素报错得解决

其实报错得原因就是抛出异常,违背了fail-fast 保护机制 此时我们换做迭代器来实现循环 List<String> list=new ArrayList<>(); list.add("1"); list.add("2"); Iterator<String> iterator=list.iterator(); while(iterator.hasNext()){ String item=iterator.next(); if(删除元素得条件){

qq_41144042的博客 894

为什么在for each 循环里 remove 会报错

如下代码:

挨踢newbie的专栏 1286

C#中出现“集合已修改;可能无法执行枚举操作”错误 foreach list.Remove()

原因:  在循环的时候,当集合被删除了一个item后,那么总数 count和索引就会发生改变.所以会报错 解决方法: 不要在枚举集合的操作(例如foreach)中去执行修改集合的操作。如果需要修改集合,那么你应该先使用 ToArray() 方法,例如 C# code ? 1 2 3 4 foreach 

u010032207的专栏 1万+

foreach中移除(remove)元素 问题汇总

1,ArrayList 移除元素时,有时候报错,有时候不报错List&lt;String&gt; a = new ArrayList&lt;&gt;(); a.add("1"); a.add("2"); for (String temp : a) { if("1".equals(temp)){ ...

tmplayer的博客 1万+

foreach循环中为什么不要进行remove/add操作

先来看一段代码,摘自阿里巴巴的java开发手册 1 List<String> a = new ArrayList<String>(); 2 a.add("1"); 3 a.add("2"); 4 for (String temp : a) { 5 if("1".equals(temp)){ 6 a.remove(temp);...

weixin_30457881的博客 306

ArrayList 和 List 集合类型

ArrayList 或 List 对象是较为复杂的数组。ArrayList 类和 List 泛型类提供多数 System.Collections 类都提供的但 Array 类未提供的一些功能。例如: Array 的容量是固定的,而 ArrayList 或 List 的容量可根据需要自动扩充。如果更改了 Capacity 属性的值,则可以自动进行内存重新分配和元素复制。 ArrayLis

绝凌峰 506
上一篇: 关于ArrayList
下一篇: 关于两个对象的比较
wangleon
博客等级 码龄20年 0粉丝 5原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值