Java中List迭代過程中刪除、新增元素的處理

異常信息:

java.util.ConcurrentModificationException

at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at myDemo.MyTest.testIterator(MyTest.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)

at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

代碼:

@Test
	public void testIterator (){
		//測試ArrayList迭代過程中刪除元素,
		//避免拋出 java.util.ConcurrentModificationException
		List<User> list  = new ArrayList<User>();
		for(int i = 0 ; i < 10 ; i ++){
			list.add(new User(i+""));
		}
		for(User temp:list){
			if(Integer.parseInt(temp.name) % 2 == 0){
				list.remove(temp);   //這裏引起異常,這種迭代方式新增刪除都會引起異常
			}
			System.out.print(temp.name + ",");
		}
		System.out.println("=====");
		Iterator<User> it = list.iterator();
		while(it.hasNext()){        //正確做法
			//System.out.println(it.hasNext());
			User temp = it.next();  
			if(Integer.parseInt(temp.name) % 2 == 0){
				it.remove();
			} 
		}
		
		for(User temp:list){
			System.out.print(temp.name + ",");
		}
		
		
	}
class User{
   String name = "";
   public User(String name){
       this.name = name;
   }
}

問題分析:從API中可以看到List等Collection的實現並沒有同步化,如果在多線程應用程序中出現同時訪問,而且出現修改操作的時候都要求外部操作同步化;調用Iterator操作獲得的Iterator對象在多線程修改Set的時候也自動失效,並拋出java.util.ConcurrentModificationException。這種實現機制是fail-fast,對外部的修改並不能提供任何保證。

Iterator是工作在一個獨立的線程中,並且擁有一個 mutex鎖,就是說Iterator在工作的時候,是不允許被迭代的對象被改變的。Iterator被創建的時候,建立了一個內存索引表(單鏈表),這 個索引表指向原來的對象,當原來的對象數量改變的時候,這個索引表的內容沒有同步改變,所以當索引指針往下移動的時候,便找不到要迭代的對象,於是產生錯誤。List、Set等是動態的,可變對象數量的數據結構,但是Iterator則是單向不可變,只能順序讀取,不能逆序操作的數據結構,當 Iterator指向的原始數據發生變化時,Iterator自己就迷失了方向。


解決辦法:調用其接口即Irerator的remove方法。

                Iterator<User> it = list.iterator();
		while(it.hasNext()){        //正確做法
			//System.out.println(it.hasNext());
			User temp = it.next();  
			if(Integer.parseInt(temp.name) % 2 == 0){
				it.remove();
			} 
		}


參考資料:http://www.cnblogs.com/dolphin0520/p/3933551.html


發佈了38 篇原創文章 · 獲贊 10 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章