2019獨角獸企業重金招聘Python工程師標準>>>
首先是兩段代碼的執行結果:
代碼一:
public class TestListRemove {public static void main(String[] args) {List<Integer> list = new ArrayList<Integer>();list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);list.add(6);list.add(7);for (Iterator<Integer> it = list.iterator(); it.hasNext();) {Integer val = it.next();if (val == 1) {list.remove(val);}}for (Integer i : list) {System.out.println(i);}}
}
代碼二:
public class TestListRemove {public static void main(String[] args) {List<Integer> list = new ArrayList<Integer>();list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);list.add(6);list.add(7);for (Iterator<Integer> it = list.iterator(); it.hasNext();) {Integer val = it.next();if (val == 6) {list.remove(val);}}for (Integer i : list) {System.out.println(i);}}
}
代碼一結果:
Exception in thread "main" java.util.ConcurrentModificationException
?? ?at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
?? ?at java.util.ArrayList$Itr.next(ArrayList.java:791)
?? ?at com.odling.test.TestListRemove.main(TestListRemove.java:21)
?
代碼二結果:
1
2
3
4
5
7
?
原因就是這里:
首先代碼一拋錯是這段代碼:
Integer val = it.next();?
final void checkForComodification() {if (modCount != expectedModCount)throw new ConcurrentModificationException();}
這個異常網上很多文章就不說了。
AbsrtactList中iteraor方法返回一個內部類,這個類實現了iterator接口,hasNext()對cursor和list的size判斷。
關于cursor的參數說明:
int cursor; ? ? ? // index of next element to return
如果刪除了倒數第二個元素,拿代碼二舉栗子:cursor返回6,size因為被remove掉一個,所以也是6,hasNext()方法返回false,不會再執行Integer val = it.next(); ?所以代碼二沒有異常,但是元素確實被remove了。
public boolean hasNext() {return cursor != size();}
?
再來看一下對代碼一的改進:
public static void main(String[] args) {List<Integer> list = new ArrayList<Integer>();list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);list.add(6);list.add(7);for (Iterator<Integer> it = list.iterator(); it.hasNext();) {try {Integer val = it.next();if (val == 1) {list.remove(val);}} catch (Exception e) {System.out.println("發生異常。");break;}}for (Integer i : list) {System.out.println(i);}}
結果:
發生異常。
2
3
4
5
6
7
?
發現元素確實已經被remove掉了。