Why doesnt hasnext,hasprevious etc methods of Iterator or listIterator check for ConcurrentModificationException

巧了我就是萌 提交于 2020-01-15 06:18:47

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!