Over my holidays I had some time to read some books from cover to cover. Since my family requested a good amount of attention, I managed to finish only two, but this is fine as I'm in the middle of the next.
Where is the issue in this code?
There are many ways to iterate through lists in Java. One of my favorite is this one:for (int i = 0; i < list.size(); ++i) {
Object obj = list.get(i);
// do something
}I developed a habit to change it into this form:for (int i = 0, size = list.size(); i < size; ++i) {
Object obj = list.get(i);
// do something
}It is at least faster then the first version. Yes, it is. Consider a type of Vector with all methods synchronized for the list...
But, where is the issue?
Comments (6)
Best way to iterate over a collection, IMHO:
for(Iterator i=list.iterator(); i.hasNext();) {
SomeClass sc = (SomeClass) i.next();
}
Use an iterator and limit its scope.
Of course with Java 5 you would use a generic iterator and then you don't need the cast. Or even better use the enhanced for loop if the scenario allows it:
for(SomeClass sc : list) {
}
Posted by Robbie Vanbrabant | August 23, 2007 2:26 AM
Posted on August 23, 2007 02:26
I assume that the reason it is faster is that the size of the list is only determined once, rather than during each iteration. In which case the potential issue would be if the list changes size during the course of the iteration (eg in the "do something" section)
Posted by Gary | August 23, 2007 4:58 AM
Posted on August 23, 2007 04:58
The issue is the list might change in size. Enlarging it is no problem, but deleting items from the list might get you into trouble, since you only check its size at the beginning of the loop.
Posted by SwitchBL8 | August 23, 2007 5:20 AM
Posted on August 23, 2007 05:20
I use this style myself all the time - if applicable. One must take care to use that idiom only with random access lists! Sequential lists like LinkedList yield poor performance. I wonder if any of the coding checkers already provides a test for this case.
Posted by Marco Hunsicker | August 23, 2007 6:36 AM
Posted on August 23, 2007 06:36
++i ?? -> i++
Posted by Sebastien Pouillet | August 23, 2007 4:16 PM
Posted on August 23, 2007 16:16
I would observe that both have the potential issue of the list changing size whilst iterating over it, the latter just has a larger window for that to happen.
To have the best chance of detecting concurrent modification to the list then use the iterators as they have a fail-fast feature - see http://java.sun.com/j2se/1.4/docs/api/java/util/ConcurrentModificationException.html
Posted by Antony Reynolds | August 24, 2007 2:58 AM
Posted on August 24, 2007 02:58