Sunday, December 24, 2006

Java 5 Feature: An intro to foreach

Looping is a control structure that has been around ever since we started programming. The good old syntax for looping that you would have used most often is:

String[] messages = {"Hello", "Greetings", "Thanks"};
var length = messages.length;
var int i = 0;
for(i = 0; i < length; i++){

What if you want to iterate over a collection, like ArrayList? We will do something like:

Iterator iter = lst.iterator();
for(;iter.hasNext();) {

The foreach was introduced to avoid introduction of any new keywords. The foreach introduced in Java 5 simplifies looping further. Let’s take a look at an example of how we can use the new way to loop:

for (String msg : messages) {

You would read
for (String msg : messages)

as "foreach String msg in messages". Within the loop of foreach, msg represents a String element within the array String[].
Instead of inventing another keyword "foreach", Sun decided to use the good old "for". Also, "in" may be used in existing code forfields, variables, or methods. In order to avoid stepping over your toes, they decided to use the ":" instead.

Using foreach with a List
ArrayList lst = new ArrayList();

for (Iterator iter = lst.iterator(); iter.hasNext();) {
for (Object o : lst) {

ArrayList values = new ArrayList();
int total = 0;
for (int val : values) {
total += val;
System.out.println("Total : " + total);

Can you use foreach on your own class?

You can do that, provided your class implements the Iterable interface. It is pretty simple. For foreach to work, you must return an Iterator. Of course, you know that Collection provides the iterator. However, for you to use foreach on your own class, the use of Collection would have made your class quite bulkier; the Iterable interface has just one method interate().

Pros and Cons:
  • Foreach looks simpler, elegant, and is easier to use
  • You can’t use it all the time, however. If you need access to the index in a collection (for setting or changing values) or you want access to the iterator (for removing an element, for instance), then you can’t use the foreach.
  • Users of your class will not be able to use foreach on your object if you don’t implement the Iterable interface.

Refer to Sun's Java Tutorial for more info.

No comments:


Popular Posts (Last 30 days)

This is a personal blog and I do not speak for my employer.