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.