Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this Java code correct?

I am having a discussion (read argument!) with one of my colleagues. I maintain that this code is very wrong but he thinks there is nothing wrong with it:

for (Iterator<String> iter = collectionOfStrings.iterator(); iter.hasNext();) {
   String item = iter.next();
   ...
}

I maintain that this code is wrong because there is a duplication of looping. Either use Iterator or use a For loop but there is no need to use them both at the same time.

I would re-write the code as follows:

Iterator<String> iter = collectionOfStrings.iterator();
while (iter.hasNext()) {
   String item = iter.next();
   ...
}

What do you think?

like image 623
Tone Avatar asked Nov 28 '22 08:11

Tone


1 Answers

Neither code is not "wrong", in the sense that both do what is expected. The second code, although equivalent, pollutes the local variables, because iter remains defined after the loop ends.

like image 113
Javier Avatar answered Dec 04 '22 16:12

Javier