哈嘍,大家好,我是了不起。
通常1-3年工作經驗的程序員算是初級程序員,再往后基本上就是在編程領域有了一定經驗的高級程序員了。
但是最近公司代碼review時,我居然發現一個 5 年工作經驗的程序員,使用 ArrayList 居然用 forEach 遍歷刪除元素?
由于公司代碼有一定敏感,我這里把代碼進行脫敏,大家一起來看看:
public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(Arrays.asList("1", "2", "3")); list.forEach(item -> { if (item.startsWith("1")) { list.remove(item); } });}
乍看之下,這段代碼似乎沒什么問題。但實際運行時,它會拋出ConcurrentModificationException異常。
這是為什么呢?我們運行這段代碼,報錯如下 :
圖片
其實 forEach 是一個語法糖,我們編譯后的代碼如下:
//這是一顆語法糖,編譯后相當于:for(Iterator i = lists.iterator();i.hasNext();){ String s = (String)i.next(); if(s.startsWith("1")){ list.remove(s); }}
然后這里的 i.next() 方法:
public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i];}final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException();}
這樣就很明了了,在Java中,當我們試圖在遍歷一個集合的同時修改它時,就會遇到ConcurrentModificationException。這是因為ArrayList的迭代器設計為快速失敗(fail-fast),即在檢測到集合在迭代期間被修改時立即拋出異常。
Iterator<String> iterator = list.iterator();while (iterator.hasNext()) { String item = iterator.next(); if (item.startsWith("1")) { iterator.remove(); }}
這種方法可以保證在刪除元素的同時不會破壞迭代器的狀態。
從Java 8開始,ArrayList引入了removeIf方法,這是刪除元素的另一種便捷方式:
list.removeIf(item -> item.startsWith("1"));
最后一種方法是首先收集所有需要刪除的元素,然后再進行刪除:
List<String> itemsToRemove = list.stream() .filter(item -> item.startsWith("1")) .collect(Collectors.toList());list.removeAll(itemsToRemove);
本文鏈接:http://www.www897cc.com/showinfo-26-57900-0.html五年程序員使用ArrayList居然用forEach遍歷刪除元素?
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 推薦一個13k的微服務編排引擎Netflix Conductor
下一篇: 20 個讓用戶驚嘆不已的按鈕效果