Nelz's Blog

16 April 2008

Java 5 FOREACH Syntax

Filed under: Java — nelz9999 @ 21:35

For those that don’t currently use the new Java 5 "foreach" syntax, you are missing out.

I got to a point today where I wanted to verify that the construct is doing the intelligent thing, so I wrote the following unit test:

@Test
public void forEachLoop() {
for (String str : doHeavyWeigthMethod()) {
System.out.println(str);
}
}
private List<String> doHeavyWeigthMethod() {
System.out.println("heavyMethod");
final List<String> results = new ArrayList<String>();
results.add("one");
results.add("two");
results.add("three");
return results;
}

I was psyched to see the output:

heavyMethod
one
two
three

Basically, this shows that the foreach construct only evaluates the collection once and caches the value to be used in each iteration.

However, the construct is not without some pitfalls. I would have expected the new construct to be programmed more defensively, but it is still susceptible to NullPointerException. Running the following throws the NPE:

@Test
public void forEachLoop() {
for (String str : doHeavyWeigthMethod()) {
System.out.println(str);
}
}
private List<String> doHeavyWeigthMethod() {
return null;
}

So, unless you know you are in control of the method you are calling in the expression part of the "foreach" construct, you still need to defensively check for null. And, we all know how much I love that, right?

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Silver is the New Black. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.