This article mainly wants to tell me about a previous article that I saw. If there is a discrepancy between your ideas, please leave a message. discussed together. #3. Delete a list element in a loop
Consider the following code. To delete an element during an iteration:
arraylist<string> list = new Arraylist<string> (Arrays.aslist ("A", "B", "C", "D")); for (int i = 0; i < list. Size (); i++) {list.remove (i);} SYSTEM.OUT.PRINTLN (list);
The output of this code is:
[B, D]
There is a serious problem with this approach. When the element is removed, the size of the list is reduced. The element index also changed. So, suppose you want to delete multiple elements within a loop by using an index. will result in incorrect results.
You might guess that you can use iterator to delete elements in a loop.
The Foreach Loop in Java works like a iterator. But it can also happen here.
Take a look at the following code:
arraylist<string> list = new Arraylist<string> (Arrays.aslist ("A", "B", "C", "D")); for (String s:list) {if (S.equals ("a")) List.remove (s);}
The Foreach Loop code above throws an exception concurrentmodificationexception. But the following code does not.
arraylist<string> list = new Arraylist<string> (Arrays.aslist ("A", "B", "C", "D"));iterator<string> iter = List.iterator (), while (Iter.hasnext ()) {String s = iter.next (); if (S.equals ("a")) {Iter.remove ();}}
By analyzing the original Code of Arraylist.iterator (), we are able to find that the next () method must be called before the Remove () method.
In the Foreach Loop. The code generated by the compiler invokes the next () method, resulting in an exception.
This is a copy of the above paragraph. but I went to see the source code and tested it and found it was not.
The error is not caused by calling the next () method first or by calling the Remove () method first. Instead, the difference between the Remove () and the Remove (Object o). View the source code and be able to see a "Expectedmodcount = Modcount" in the Remove () method; Statement, while the remove (Object O) method is this "modcount++;" It did not deal with the expectedmodcount. Causes an error in the Checkforcomodification () method to infer "Expectedmodcount = = Modcount".
So whenever you just call the Remove (Object O) method, and then you call the next () method. are bound to report concurrentmodificationexception this anomaly.
This is the case with the " foreach Loop above" described above.
You can try to put the remove () method before the next () method, it can be used.
Deleting a list element in a Java loop