Tips on Java Enhanced For Loop
By Angsuman Chakraborty, Gaea News NetworkMonday, November 14, 2005
After enhanced for loop was introduced with J2SE 1.5.x aka J5SE, I made it a delightful habit to use it. You know what I am talking about, right?
For example previously I used to write:
private gbWay() {
....
for (Iterator
Now I write:
private gbWay() {
....
for (Country c:countries) {
if(!c.isCrony()) c.attack();
}
....
}
Isn’t it simpler? You bet.
However this beauty doesn’t work everywhere. First of all you cannot use it in cases where you need to access the Iterator itself like:
for (Iterator
You cannot also use it when you want to add elements to the Collection which you are iterating. In fact you cannot use Iterator also. Can you guess how would you do it?
December 11, 2005: 11:44 pm
Good note what he’s shown here…I think generic added for loop shud only be touched (to add new for loop) to implement simple and pure hesNext() kind of check while iterating only…other iteration addtion etc. shud be made verbose to make it readable…maybe creating a handle before u go inside the loop can help..is it? |
Sourav