Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.
Scope. That’t what you need. Iterators should be given the smallest scope possible, always as local variables. Your Iterator is still in scope when you get to the removeLast() invocation, so restrict its scope with an additional pair of{}. You will of course need a new Iterator for the second loop.
It would have been better to use a for‑each loop (= enhanced for loop).
so restrict its scope with an additional pair of{}
What i don't understand is why the exception is coming?
also if I comment out at line 27 and uncomment line no 29, I would not get the error but in that case the last while loop will not work. Why?
The ListIterator has reached the end so it is not printing. Make it hasPrevious and it prints.
If I have understood properly, line no 27 is modifying the ListIterator collection.....that means after line 27 the underlying Iterator is not stable anymore.
that is why even if I change line no 31 from
view plaincopy to clipboardprint?
lit.hasnext()
to
view plaincopy to clipboardprint?
lit.hasPrevious()
, even though its not working and still throwing exception.
Am I correct?
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |