How do you iterate your lists?
This seems to be a matter of personal preference, but I'm interested in hearing how other programmers do their loops. Here's how I do it most often:
List users = dao.getUsers();
for (int i=0; i < users.size(); i++) {
User user = (User) users.get(i);
// do something with user
}
I've seen others do it with an Iterator, and I've done it this way myself, but for some reason I prefer the for loop:
List users = dao.getUsers();
Iterator userIter = users.iterator();
while (userIter.hasNext()) {
User user = (User) userIter.next();
// do something with user
}
I usually add a null check as part of the loop as well. They both seem pretty much the same to me - is one more performant than the other? John Watkinson points out that in JDK 1.5, the for loop will be even easier:
List users = dao.getUsers();
for (User user : list) {
// do something with user
At least that's how I interpreted it - please correct me if I'm wrong. Also, enlighten me if I should be using an Iterator - or at least let me know what advantages it has over a for loop.
User user = (User) iterator.next();
// do something with the user
}
There's one main reason why this is how I iterate collections. It doesn't reveal any internal implementation details, and it doesn't assume anything about the best method for iterating the collection. I don't do much work with the List interface often. Only when I need the features it provides that the Collection interface lacks. This way, I can work with List and Set collections without adjusting my code. Let the collection worry about how to iterate over its elements. that's not my job.
The other reason is that it doesn't pollute your namespace outside of your loop. But that's ancillary.
Jesse
Posted by Jesse Blomberg on May 12, 2003 at 10:32 PM MDT #
Posted by Paul Rivers on May 12, 2003 at 10:43 PM MDT #
Posted by Kasper Nielsen on May 12, 2003 at 11:31 PM MDT #
Posted by Ryan on May 14, 2003 at 02:09 AM MDT #
This came in very handy, when we had to operate on very large data sets. We implemented an iterator on top of an ObjectInputStream and thus were able to put the data sets into temporary files.
When our server was equipped with more RAM, we could switch back to memory-based collections without much ado.
Posted by Fokko Degenaar on May 14, 2003 at 07:11 AM MDT #
Posted by Robert Nicholson on May 16, 2003 at 12:58 PM MDT #