Java for each loop working

前端 未结 5 783
无人及你
无人及你 2021-01-14 08:53

I was working on certain task, when incidentally did something wrong according to me but the code executed and provided correct result. I was little surpris

5条回答
  •  有刺的猬
    2021-01-14 09:21

    A for-each loop is possible for Classes that implement Iterable. This also means that you can create Classes yourself which you can use in for-each loops, which can be very comfortable.

    This interface forces you to implement a method iterator() which returns an Iterator. Then the for-each loop does nothing but retrieve that iterator and iterate over it using hasNext() and next(). Just the same as you would do it yourself.

    The problem with removing is that when you use a for-each loop and then remove an element from the List, the constructed Iterator will not know anything about that change and there will be a ConcurrentModificationException.

    But if you call Iterator.remove() directly, the Iterator will know about that change and can handle it.

    A common little trick to avoid Iterators and Exceptions at the same time is to do something like this:

    List objects = new ArrayList();
    for (Object object : new ArrayList(objects)) {
        objects.remove(object);
    }
    
    
    

    So you create a temporary copy of that List, iterate over that, but call remove on the original List.

    提交回复
    热议问题