自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

為什么阿里巴巴強(qiáng)制不要在 Foreach 里執(zhí)行刪除操作

開發(fā) 前端
很多時(shí)候,我們會(huì)把 fail-fast 歸類為 Java 集合框架的一種錯(cuò)誤檢測(cè)機(jī)制,但其實(shí) fail-fast 并不是 Java 集合框架特有的機(jī)制。

[[430039]]

為了鎮(zhèn)樓,先搬一段英文來解釋一下 fail-fast。

In systems design, a fail-fast system is one which immediately reports at its interface any condition that is likely to indicate a failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly flawed process. Such designs often check the system's state at several points in an operation, so any failures can be detected early. The responsibility of a fail-fast module is detecting errors, then letting the next-highest level of the system handle them.

這段話的大致意思就是,fail-fast 是一種通用的系統(tǒng)設(shè)計(jì)思想,一旦檢測(cè)到可能會(huì)發(fā)生錯(cuò)誤,就立馬拋出異常,程序?qū)⒉辉偻聢?zhí)行。

  1. public void test(Wanger wanger) {    
  2.     if (wanger == null) { 
  3.         throw new RuntimeException("wanger 不能為空"); 
  4.     } 
  5.      
  6.     System.out.println(wanger.toString()); 

一旦檢測(cè)到 wanger 為 null,就立馬拋出異常,讓調(diào)用者來決定這種情況下該怎么處理,下一步 wanger.toString() 就不會(huì)執(zhí)行了——避免更嚴(yán)重的錯(cuò)誤出現(xiàn)。

很多時(shí)候,我們會(huì)把 fail-fast 歸類為 Java 集合框架的一種錯(cuò)誤檢測(cè)機(jī)制,但其實(shí) fail-fast 并不是 Java 集合框架特有的機(jī)制。

之所以我們把 fail-fast 放在集合框架篇里介紹,是因?yàn)閱栴}比較容易再現(xiàn)。

  1. List<String> list = new ArrayList<>(); 
  2. list.add("沉默王二"); 
  3. list.add("沉默王三"); 
  4. list.add("一個(gè)文章真特么有趣的程序員"); 
  5.  
  6. for (String str : list) { 
  7.  if ("沉默王二".equals(str)) { 
  8.   list.remove(str); 
  9.  } 
  10.  
  11. System.out.println(list); 

這段代碼看起來沒有任何問題,但運(yùn)行起來就報(bào)錯(cuò)了。

根據(jù)錯(cuò)誤的堆棧信息,我們可以定位到 ArrayList 的第 901 行代碼。

  1. final void checkForComodification() { 
  2.     if (modCount != expectedModCount) 
  3.         throw new ConcurrentModificationException(); 

也就是說,remove 的時(shí)候觸發(fā)執(zhí)行了 checkForComodification 方法,該方法對(duì) modCount 和 expectedModCount 進(jìn)行了比較,發(fā)現(xiàn)兩者不等,就拋出了 ConcurrentModificationException 異常。

為什么會(huì)執(zhí)行 checkForComodification 方法呢?

是因?yàn)?for-each 本質(zhì)上是個(gè)語法糖,底層是通過迭代器 Iterator 配合 while 循環(huán)實(shí)現(xiàn)的,來看一下反編譯后的字節(jié)碼。

  1. List<String> list = new ArrayList(); 
  2. list.add("沉默王二"); 
  3. list.add("沉默王三"); 
  4. list.add("一個(gè)文章真特么有趣的程序員"); 
  5. Iterator var2 = list.iterator(); 
  6.  
  7. while(var2.hasNext()) { 
  8.     String str = (String)var2.next(); 
  9.     if ("沉默王二".equals(str)) { 
  10.         list.remove(str); 
  11.     } 
  12.  
  13. System.out.println(list); 

來看一下 ArrayList 的 iterator 方法吧:

  1. public Iterator<E> iterator() { 
  2.     return new Itr(); 

內(nèi)部類 Itr 實(shí)現(xiàn)了 Iterator 接口。

  1. private class Itr implements Iterator<E> { 
  2.     int cursor;       // index of next element to return 
  3.     int lastRet = -1; // index of last element returned; -1 if no such 
  4.     int expectedModCount = modCount; 
  5.  
  6.     Itr() {} 
  7.  
  8.     public boolean hasNext() { 
  9.         return cursor != size
  10.     } 
  11.  
  12.     @SuppressWarnings("unchecked"
  13.     public E next() { 
  14.         checkForComodification(); 
  15.         int i = cursor
  16.         Object[] elementData = ArrayList.this.elementData; 
  17.         if (i >= elementData.length) 
  18.             throw new ConcurrentModificationException(); 
  19.         cursor = i + 1; 
  20.         return (E) elementData[lastRet = i]; 
  21.     } 

也就是說 new Itr() 的時(shí)候 expectedModCount 被賦值為 modCount,而 modCount 是 List 的一個(gè)成員變量,表示集合被修改的次數(shù)。由于 list 此前執(zhí)行了 3 次 add 方法。

  • add 方法調(diào)用 ensureCapacityInternal 方法
  • ensureCapacityInternal 方法調(diào)用 ensureExplicitCapacity 方法
  • ensureExplicitCapacity 方法中會(huì)執(zhí)行 modCount++

所以 modCount 的值在經(jīng)過三次 add 后為 3,于是 new Itr() 后 expectedModCount 的值也為 3。

執(zhí)行第一次循環(huán)時(shí),發(fā)現(xiàn)“沉默王二”等于 str,于是執(zhí)行 list.remove(str)。

  • remove 方法調(diào)用 fastRemove 方法
  • fastRemove 方法中會(huì)執(zhí)行 modCount++
  1. private void fastRemove(int index) { 
  2.     modCount++; 
  3.     int numMoved = size - index - 1; 
  4.     if (numMoved > 0) 
  5.         System.arraycopy(elementData, index+1, elementData, index
  6.                          numMoved); 
  7.     elementData[--size] = null; // clear to let GC do its work 

modCount 的值變成了 4。

執(zhí)行第二次循環(huán)時(shí),會(huì)執(zhí)行 Itr 的 next 方法(String str = (String) var3.next();),next 方法就會(huì)調(diào)用 checkForComodification 方法,此時(shí) expectedModCount 為 3,modCount 為 4,就只好拋出 ConcurrentModificationException 異常了。

那其實(shí)在阿里巴巴的 Java 開發(fā)手冊(cè)里也提到了,不要在 for-each 循環(huán)里進(jìn)行元素的 remove/add 操作。remove 元素請(qǐng)使用 Iterator 方式。

那原因其實(shí)就是我們上面分析的這些,出于 fail-fast 保護(hù)機(jī)制。

那該如何正確地刪除元素呢?

1)remove 后 break

  1. List<String> list = new ArrayList<>(); 
  2. list.add("沉默王二"); 
  3. list.add("沉默王三"); 
  4. list.add("一個(gè)文章真特么有趣的程序員"); 
  5.  
  6. for (String str : list) { 
  7.  if ("沉默王二".equals(str)) { 
  8.   list.remove(str); 
  9.   break; 
  10.  } 

break 后循環(huán)就不再遍歷了,意味著 Iterator 的 next 方法不再執(zhí)行了,也就意味著 checkForComodification 方法不再執(zhí)行了,所以異常也就不會(huì)拋出了。

但是呢,當(dāng) List 中有重復(fù)元素要?jiǎng)h除的時(shí)候,break 就不合適了。

2)for 循環(huán)

  1. List<String> list = new ArrayList<>(); 
  2. list.add("沉默王二"); 
  3. list.add("沉默王三"); 
  4. list.add("一個(gè)文章真特么有趣的程序員"); 
  5. for (int i = 0, n = list.size(); i < n; i++) { 
  6.  String str = list.get(i); 
  7.  if ("沉默王二".equals(str)) { 
  8.   list.remove(str); 
  9.  } 

for 循環(huán)雖然可以避開 fail-fast 保護(hù)機(jī)制,也就說 remove 元素后不再拋出異常;但是呢,這段程序在原則上是有問題的。為什么呢?

第一次循環(huán)的時(shí)候,i 為 0,list.size() 為 3,當(dāng)執(zhí)行完 remove 方法后,i 為 1,list.size() 卻變成了 2,因?yàn)? list 的大小在 remove 后發(fā)生了變化,也就意味著“沉默王三”這個(gè)元素被跳過了。能明白嗎?

remove 之前 list.get(1) 為“沉默王三”;但 remove 之后 list.get(1) 變成了“一個(gè)文章真特么有趣的程序員”,而 list.get(0) 變成了“沉默王三”。

3)使用 Iterator

  1. List<String> list = new ArrayList<>(); 
  2. list.add("沉默王二"); 
  3. list.add("沉默王三"); 
  4. list.add("一個(gè)文章真特么有趣的程序員"); 
  5.  
  6. Iterator<String> itr = list.iterator(); 
  7.  
  8. while (itr.hasNext()) { 
  9.  String str = itr.next(); 
  10.  if ("沉默王二".equals(str)) { 
  11.   itr.remove(); 
  12.  } 

為什么使用 Iterator 的 remove 方法就可以避開 fail-fast 保護(hù)機(jī)制呢?看一下 remove 的源碼就明白了。

  1. public void remove() { 
  2.     if (lastRet < 0) 
  3.         throw new IllegalStateException(); 
  4.     checkForComodification(); 
  5.  
  6.     try { 
  7.         ArrayList.this.remove(lastRet); 
  8.         cursor = lastRet; 
  9.         lastRet = -1; 
  10.         expectedModCount = modCount; 
  11.     } catch (IndexOutOfBoundsException ex) { 
  12.         throw new ConcurrentModificationException(); 
  13.     } 

刪除完會(huì)執(zhí)行 expectedModCount = modCount,保證了 expectedModCount 與 modCount 的同步。

簡單地總結(jié)一下,fail-fast 是一種保護(hù)機(jī)制,可以通過 for-each 循環(huán)刪除集合的元素的方式驗(yàn)證這種保護(hù)機(jī)制。 

那也就是說,for-each 本質(zhì)上是一種語法糖,遍歷集合時(shí)很方面,但并不適合拿來操作集合中的元素(增刪)。

本文轉(zhuǎn)載自微信公眾號(hào)「沉默王二」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系沉默王二公眾號(hào)。

 

責(zé)任編輯:武曉燕 來源: 沉默王二
相關(guān)推薦

2023-04-03 07:03:51

阿里巴巴List元素

2019-03-04 09:22:52

阿里巴巴foreach Java

2021-10-11 09:32:40

包裝類型屬性

2018-10-16 15:34:17

阿里巴巴Apache Flin大數(shù)據(jù)

2013-08-22 09:26:38

去IOE王堅(jiān)

2016-09-21 20:28:55

阿里巴巴IOE

2021-08-04 17:20:30

阿里巴巴AsyncJava

2019-09-04 11:02:54

繼承層次組合

2020-09-14 09:47:56

Java開發(fā)類型

2021-09-07 17:22:43

阿里巴巴辭職高薪

2019-09-02 15:20:28

Java開發(fā)繼承

2010-06-28 10:43:47

2020-09-08 16:25:18

Apache BeancopyJava

2022-09-05 10:06:21

MySQL外循環(huán)內(nèi)循環(huán)

2019-06-26 07:54:53

ArrayListsubList源碼

2020-07-30 12:16:33

阿里巴巴Apache對(duì)象

2013-08-22 09:41:52

阿里巴巴去IOE王堅(jiān)

2020-09-22 11:40:53

BigDecimalequalsJava

2025-04-17 08:47:23

2012-09-17 10:20:11

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)