I was just curious on how multiple iterators on a single object would behave and typed in the following code.
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
class Test{
public static void main(String[] a) {
Map<Integer,String> map = new HashMap<>();
map.put(1,"One");
Iterator<Integer> it1 = map.keySet().iterator();
Iterator<Integer> it2 = map.keySet().iterator();
it1.next();
it1.remove();
System.out.println(it2.hasNext());
System.out.println(it2.next());
System.out.println(map.get(1));
}
}
The map is empty as expected But, i thought Iterator#hasNext
would return false
, but instead it returned true
and Iterator#next
threw a ConcurrentModificationException
.
when a value is removed from a Collection
using the Iterator#remove
method shouldn't the other iterator's hasNext
method return false, as there wouldn't be any value to be returned?
The hasNext
method only checks the next
attribute:
public final boolean hasNext() {
return next != null;
}
and the only method that modifies the next
attribute are:
Which means that if you a few Iterator
instances pointing to the same collection instance only when you call one of the above two methods the Iterator will access the underlying collection and check whether its state has change.
Please note that if the underlying collection is modified the behavior of an iterator is unspecified , which means it might be changed and you should not depend on it.
The javadoc for iterator.remove()
states:
The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
And that is precisely what is happening in your code, the underlying collection is being modified for more than one iterator.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.