鍦ㄥ綰跨▼涓嬩嬌鐢↖terator鏉ヨ凱浠e璞℃椂錛屾諱細鍖匔oncurrentModificationException();寮傚父錛岀粡榪囨垜瀵筶ist鍜孖terator鐩稿叧婧愮爜鐨勫垎鏋愶紝緇堜簬鎼炴槑鐧戒簡榪欎釜闂錛?nbsp;
涓嬮潰緇撳悎婧愪唬鐮佹潵璁ㄨ榪欎釜闂錛?br />
1銆佸綋鎴戜滑璋冪敤涓涓狶ist鐨刬terator鏃訛紝鍏跺疄榪斿洖鐨勫茍涓嶆槸Itr瀵硅薄錛圛terator鏄竴涓帴鍙o級錛岃鐪嬩唬鐮侊細
1
public Iterator<E> iterator()
{
2
return new Itr();
3
}
2銆佸湪Itr綾諱腑鏈夎繖涔堜竴鍙ヨ瘽 int expectedModCount = modCount;棣栧厛璁蹭竴涓嬭繖涓や釜鍙橀噺鐨勫惈涔夛細
expectedModCount 錛氬垱寤哄綋鍓嶇殑Itr瀵硅薄鏃墮泦鍚堝璞¤淇敼鐨勬鏁般備粬鏄疘tr鐨勫彉閲忋?br />
modCount錛氳褰曢泦鍚堝璞′粠鍒涘緩鍒板綋鍓嶆椂闂磋鍋氫慨鏀圭殑嬈℃暟銆傦紙闆嗗悎姣忚繘琛屼竴嬈″鍒犳敼鏌ラ兘浼氫嬌modCount錛夛紝浠栨槸Itr鐨勫閮ㄧ被AbstractList
鐨勫彉閲忥紝涓旇鍙橀噺鍦?nbsp;AbstractList涓濡傛淇グprotected transient int modCount = 0;
鍙﹀錛孖tr鑷繁瀵歸泦鍚堝璞¤繘琛屼簡淇敼鍚庯紝浠栦細緇存寔expectedModCount 鍜宮odCount鐨勪繚鎸佺浉絳夛紝璇風湅浠ヤ笅浠g爜
1 //Itr鐨勫垹闄ゆ柟娉?/span>
2 public void remove() {
3 if (lastRet == -1)
4 throw new IllegalStateException();
5 checkForComodification();
6
7 try {
8 AbstractList.this.remove(lastRet);
9 if (lastRet < cursor)
10 cursor--;
11 lastRet = -1;
12 expectedModCount = modCount;
13 } catch(IndexOutOfBoundsException e) {
14 throw new ConcurrentModificationException();
15 }
16 }
鍦ㄤ唬鐮佺殑12琛岋紝Itr淇濊瘉浜唀xpectedModCount 鍜宮odCount鍊肩殑鐩哥瓑 錛宮odCount鐨勫煎彂鐢熶簡鏀瑰彉鍚楋紝浠栨敼鍙樹簡錛屽甫浠g爜鐨勭8琛屾敼鍙樼殑錛岃鐪嬫澶勭殑浠g爜錛?br />
1
public E remove(int index)
{
2
RangeCheck(index);
3
4
modCount++;
5
E oldValue = elementData[index];
6
7
int numMoved = size - index - 1;
8
if (numMoved > 0)
9
System.arraycopy(elementData, index+1, elementData, index,
10
numMoved);
11
elementData[--size] = null; // Let gc do its work
12
13
return oldValue;
14
}
鍦ㄤ唬鐮佺殑絎洓琛宮odCount鍙戠敓浜嗘敼鍙樸?nbsp;鐢辨鍙互鐪嬪嚭錛屽湪鎴戜滑璋冪敤闆嗗悎瀵硅薄鐨刬terator()鏂規硶鐨剅emove鏃舵諱細浣縧ist鐨刴odCount鐨勫艱嚜澧?錛屼絾鏄疘tr浼氳嚜宸辯淮鎶よ鍊煎拰expectedModCount 鐨勪竴鑷淬?br />
3銆佽瘯闂細濡傛灉expectedModCount 鍜宮odCount鐨勫煎鏋滀笉鐩哥瓑錛屼細鏈変粈涔堥棶棰樺憿錛岃繖灝辨槸鎶oncurrentModificationException();寮傚父鐨勫師鍥犳墍鍦紝璇峰厛鐪婭tr鐨刵ext()鏂規硶鍜宯ext()璋冪敤鐨勬柟娉?br />
1
//Itr鐨刵ext鏂規硶錛?/span>
2
public E next()
{
3
checkForComodification();
4
try
{
5
E next = get(cursor);
6
lastRet = cursor++;
7
return next;
8
} catch(IndexOutOfBoundsException e)
{
9
checkForComodification();
10
throw new NoSuchElementException();
11
}
12
}
13
14
//checkForComodification()鏂規硶錛?/span>
15
final void checkForComodification()
{
16
if (modCount != expectedModCount)
17
throw new ConcurrentModificationException();
18
}
19
}
20
鍦╪ext鏂規硶鐨勪竴寮濮嬫樉紺鴻皟鐢ㄤ簡checkForComodification()鏂規硶錛堣絎笁琛岋級錛屽湪checkForComodification()鏂規硶涓仛鐨勫伐浣滃氨鏄瘮杈僥xpectedModCount 鍜宮odCount鐨勫兼槸鍚︾浉絳夛紝濡傛灉涓嶇浉絳夛紝灝辮涓鴻繕鏈夊叾浠栧璞℃鍦ㄥ褰撳墠鐨凩ist榪涜鎿嶄綔錛岄偅涓氨浼氭姏鍑篊oncurrentModificationException寮傚父銆?br />
緇忚繃浠ヤ笂鐨勫垎鏋愶紝鍙戠幇鎶涘嚭ConcurrentModificationException寮傚父澶勪簬璋冪敤next()鏂規硶鏃訛紝姣旇緝expectedModCount 鍜宮odCount鐨勫鹼紝濡傛灉涓や釜鍊間笉鐩哥瓑錛屽氨浼氭姏鍑哄紓甯革紝鐒惰屽湪浠涔堟儏鍐典笅浼氫嬌expectedModCount 鍜宮odCount鐨勫間笉鐩哥瓑鍛紝鍙湁鍦ㄤ袱涓狪tr鍚屾椂瀵逛竴涓猯ist榪涜鎿嶄綔鐨勬椂鍊欐墠浼氬嚭鐜拌繖鏍風殑闂錛屾墍浠ュ湪浠ュ悗鐨勭紪鐮佽繃紼嬩腑鍦ㄦ槸鐢盜terator榪涜remove()鏃朵竴瀹氳鑰冭檻鏄惁鏃跺綰跨▼鐨勶紝濡傛灉鏄涓嶈鐢↖terator榪涜remove錛堬級錛岃屽簲璇ヤ嬌鐢↙ist鐨剅emove鏂規硶榪涜銆?

]]>