« migration to squarespace | Main | best of ben »
Wednesday
Oct142009

Java foreach loops on empty collections

I've been worrying about whether I need to check for null when invoking a foreach loop on a collection that might be empty. The answer is, nope, I don't need to check for an empty list; java just Does The Right Thing.

List<Object> list = new ArrayList<Object>();
logger.info("here's a list that was always empty: " + list.toString());
for (Object o: list) {
logger.info("here's an object: " + o.toString());
}
logger.info("done");

...yields this output:
INFO: here's a list that was always empty: []
INFO: done

These alternate ways of expressing the same loop also all execute without a problem, even for an empty list:

for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
logger.info("here's an object: " + o.toString());
}
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
logger.info("here's an object: " + o.toString());
}

That's just a detail that's been bugging me, and now I understand the behavior. For what it's worth, I couldn't find this issue addressed in the JSR.

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>