Project scene:
Project scenario: iterator exception problem
Problem Description:
When using an iterator to traverse the collection, adding elements to the collection will cause the iterator to be abnormal
List list = new ArrayList<>();
list.add("曹操");
list.add("貂蝉");
Iterator it = list.iterator();
while (it.hasNext()){
if (it.next().equals("貂蝉")){
list.add("吕布");
}
}
System.out.println(list);
}
Cause Analysis:
In the case of an iterator, adding or deleting elements to the collection will cause the length of the collection to change, which will lead to errors in the judgment in the source code, resulting in an error, but if the element is modified, the error will not occur, because the modification The element does not cause the length of the collection to change.
solution:
In an iterator, do not change the length of the collection traversed by the iterator. If we need to change the length of the collection through certain conditions in the traversal, we can first put the original collection in a new collection, and use the traversal conditions of the original collection to change the length of the new collection, so It will not cause the iterator to report errors.
E.g:
List list = new ArrayList<>();
list.add("曹操");
list.add("貂蝉");
List list1 = new ArrayList<>();
list1.add("曹操");
list1.add("貂蝉");
Iterator it = list.iterator();
while (it.hasNext()){
if (it.next().equals("貂蝉")){
list1.add("吕布");
}
}
System.out.println(list1);
}