天天看點

ListIterator使用時的ConcurrentModificationException異常問題

寫作業時用到了疊代器ListIterator,主要代碼如下,使用了

.hasNext()
           
.next()
.hasPrevious()            
.previous()
           
ListIterator<Worker> it = workerList.listIterator();
		
		int index = 0;
		while(it.hasNext())
		{
			Worker w = it.next() ; 
			if("li4".equals(w.getName()))
			{
//				it.add( new Worker("zhao6",24,3300));
				index = workerList.indexOf(w);
				System.out.println(index);
//				break;
			}
		}
		workerList.add(index, new Worker("zhao6",24,3300));
		System.out.println(workerList.toString());
		
//		ListIterator<Worker> it1 = workerList.listIterator();
		while(it.hasPrevious())
		{
			Worker w = it.previous() ; 
			if("zhang3".equals(w.getName()))
			{
				it.remove();
//				break;
			}
			System.out.println(workerList.toString());
		}
           
報錯Exception in thread "main" java.util.ConcurrentModificationException,檢查後發現,是下面這句代碼的使用使程式抛出了異常
workerList.add(index, new Worker("zhao6",24,3300));
           
ListIterator   it  和集合  workList 同時操作一個資源,語句下方還有
while(it.hasPrevious())
           
即ListIterator   it 未完成對集合的操作,此時就會抛出異常 ----------------------------------------------------------------------------------------------------- 注意:使用ListIterator的
.hasNext()
           
.next()
.hasPrevious()            
.previous()
           
周遊集合時,注意可能因指針不在集合的頭或尾而"錯過"某些資料