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).
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?
Good question. I think the quote alone really emcompasses the difference and when you would choice one over the other.
For UnsupportedOperation, both will behave the same, if you are looping through a collection, Iterator or not, and call the Collections remove, then you will get this exception. If you use the new For-Each loop, you do not have access to the Iterator, so you cannot call the only way to delete from the actual Collection, which is through the Iterators delete method.