首页  

集合遍历删除注意点     所属分类 java 浏览量 1176
不要在foreach里 进行 remove/add 操作 

集合遍历使用Iterator, 集合发生变化时 , 根据 fail-fast  原则 Iterator 抛出 java.util.ConcurrentModificationException 

list 遍历删除元素的正确做法 


        Iterator<Integer> it = list.iterator();
		while(it.hasNext()){
			Integer item = it.next();
			if (item.intValue() % 2 == 0) {
				it.remove();
			}
		}


在 for 循环 里 调用 remove 可能导致的问题 

java.util.ConcurrentModificationException
java.lang.IndexOutOfBoundsException
结果不对

      try {
			for (Integer item : list) {
				if (item.intValue() % 2 == 0) {
					list.remove(item);
				}
			}
		} catch (Throwable e) {
			// java.util.ConcurrentModificationException
			System.out.println(e);
		}
		
		// 

        int num = list.size();
		try {
			for (int i=0;i<num;i++) {
				Integer item = list.get(i);
				System.out.println("i="+i+",item="+item);
				if (item.intValue() % 2 == 0) {
					list.remove(item);
				}
			}
		} catch (Throwable e) {
			// java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
			System.out.println(e);
		}
		
		// 
		
		
		// 这个结果不对 list.size() 是动态变化的 
		try {
			for (int i=0;i<list.size();i++) {
				Integer item = list.get(i);
				System.out.println("i="+i+",item="+item);
				if (item.intValue() % 2 == 0) {
					list.remove(item);
				}
			}
		} catch (Throwable e) {
			System.out.println(e);
		}			


上一篇     下一篇
Timer和ScheduledExecutorService的区别

不要在finally块中使用return

jcmd PerfCounter 说明

java编码规范

jvm热点线程定位

并发编程模型