Avoiding the copy-paste mistake when using Iterators in Java

If you’re reading this it’s probably because you’ve done something like this (iterating over two lists in same block of code):

//Iterating with no problems

Iterator<String> it = list.iterator();  

while (it.hasNext()){  

     String current = it.next;  

}  

//BUG!!!!!!

Iterator<String> it2 = list2.iterator();  

while (it2.hasNext()){  

     String current = it.next;  //Not using the correct iterator

}

Before anyone says anything, YES, YOU SHOULD USE FOREACH. But there are situations where you want access to the iterator (for instance, to remove an element using the iterator’s remove() method).

This little bug where you increment the wrong iterator variable is a pain in the neck to figure out sometimes and I read this really interesting piece of advice in Joshua Bloch’s Effective Java. Instead of using a while loop, use a for loop like this:

for (Iterator<String> it = list.iterator(); it.hasNext(); ){  

   String current = it.next();  

}

The snippet above allows you to reuse the “it” variable name as many times as you wish because, this time, the variable is declared inside the for loop thus, if you try to use it else where the compiler will generate an error (because the variable is only declared in the scope of the for loop) and you’ll avoid some debugging time 🙂

P.S – One could argue that you should iterate over each list inside separate methods, but the point of this post is to put the variable declaration in a narrower scope than the original idea (the one that creates the error in the first place).

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *