Home > database >  Java iterator
Java iterator

Time:02-04

Why output 100, here called the remove of the collection, the collection structure changed, why don't run error, I found the first debug don't go in the second cycle after cycle, not another 1000 collection? If the collection contains three elements will be an error, the two will not

CodePudding user response:

No matter what language, the object directly, such as the foreach iterator delete specify the location of the object are complains, principle is very simple, is whether an iterator object or to index iterative iterators, clockwise delete will be an error, because to join you for (I=0; I<2), at the moment when you first iteration, delete the second, the iterator hasNext finish not only detect the iteration, will also record a few iterations, you delete the second, the cycle time, the array length is 1, the cycle a 1=1, hasNext, when there is a third data, record for cycling times, at the end of the first cycle, record the index to 1, the number of iterations is 1, deleted at this time, the second array length is 2, 1 is not equal to 2, hasNext established, when the second cycle, it. The Next () error directly, because the data has no residual length

CodePudding user response:

Generally safely delete objects, to go to delete in reverse chronological order, avoid index overflow
  • Related