问题
I know that failfast iterators check for ConcurrentModificationException on best-effort basis.Why doesnt the methods such as hasnext or hasPrevious check for ConcurrentModificationException and throw it???
The following code works well for the precise reason that these methods are not checked for CME although it has been structurally modifed
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> lilong = new ArrayList<String>();
lilong.add("Queen");
for(Iterator<String> iter =lilong.iterator();iter.hasNext();)
{
System.out.println(iter.next());
lilong.add("King");
lilong.remove(0);
lilong.add("Star");
lilong.remove(0);
lilong.add("Sun");
lilong.remove(0);
lilong.add("Polar Bear");
lilong.clear();
lilong.add("There you go");
}
System.out.println("size="+ lilong.size()+"##element##"+lilong.iterator().next());
}
回答1:
hasNext for ArrayList's iterator does not check for modifications, it only looks at the size.
If you put one more element in your list, you'd get into a second iteration and then next would fail as expected.
As for why it is implemented that way... +1 to your question.
回答2:
Edit: Removed a load of crap
So the question is: why doesn't hasNext() check for concurrent modification, like the other methods of Iterator.
If I would wager a guess, hasNext() doesn't have a lot of use unless there's a next() right after. So instead of having the check in 2 places, it's just in next().
来源:https://stackoverflow.com/questions/21450191/why-doesnt-hasnext-hasprevious-etc-methods-of-iterator-or-listiterator-check-for