I'm playing around with the new
Java 5 for loop and trying to make sure I understand any differences between it and using an Iterator to deal with each element of a collection for
SCJP 5.0. I read somewhere (don't remember where) or maybe heard in a talk at JavaOne, that said that there were certain restrictions or cases where you could NOT use the new for loop, but you could use an Iterator. Specifically, I think it was in cases dealing with Unsupported Operation exceptions caused by modifying the list (e.g. doing a remove).
I've read
The For-Each Loop article that is part of
J2SE(TM) 5.0 New Features. It contains the following quote, but I'd still like to know more.
So when should you use the for-each loop? Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would cover the great majority of cases.
Could anyone suggest some good reading material that the following questions:
A) What are the differences between the new for loop and Iterators? When should each of them be used?
B) What are the specific cases where removing from a List will give an Unsupported Operation exception? Do the new for loops and Iterators behave the same way with regard to this?
Thanks,
Josh