About iterator concurrent modification anomalies

Iterator iterator :
List<String> list = new ArrayList<>();
list.add("老马");
list.add("老王");
list.add("老彭");
Iterator <String> = list.iterator Iterator (); 
the while (iterator.hasNext ()) {
IF (. Iterator.next () the equals ( "Wang")) {
the Iterator.remove (); // [horse, Laopeng]
list.remove ( "Wang"); // [horse, Laopeng]
//list.add ( "Wang +"); // a ConcurrentModificationException
}
}
System.out.println (List);
By List collection added elements, and the expected time of iterators get the elements to modify the number of values and the actual number of modifications values are not the same result 
(see specifically () code in ArrayList class iterator method in an anonymous inner class Itr implementation process).


ListIterator iterator:

The ListIterator <String> List.listIterator listIterator = (); 
the while (listIterator.hasNext ()) {
IF (listIterator.next () the equals ( "Wang").) {
//ListIterator.remove (); // [Old Ma, Laopeng]
//listIterator.add ( "Li"); // [horse, Pharaoh, talk of the town, Lao Peng]
//listIterator.set ( "Zhao change Pharaoh"); // [ horse, Zhao Wang change, Laopeng]
//list.remove ( "Wang"); // [horse, Laopeng]
List.add ( "Aberdeen ho"); // a ConcurrentModificationException
}
}
the System. out.println (list);
by List collection added element, and acquires the desired element iterative modification number value and the actual value does not modify the number of times the same result
(in particular internal ArrayList class ListIterator process anonymous ListItr () He inherited his parent class Itr () so the specific circumstances almost similar)
If you want the deletion in ListIterator iterator does not produce concurrency exception, directly call ListIterator () method itself can be.
 

Guess you like

Origin www.cnblogs.com/robotsu/p/11486139.html