Skip to main content

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++){
System.out.println(messages[i]);
}

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

Iterator iter = lst.iterator();
for(;iter.hasNext();) {
System.out.println(iter.next());
}


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) {
System.out.println(msg);
}

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();
lst.add(1);
lst.add(4.1);
lst.add("test");

for (Iterator iter = lst.iterator(); iter.hasNext();) {
System.out.println(iter.next());
}
for (Object o : lst) {
System.out.println(o);
}


ArrayList values = new ArrayList();
values.add(1);
values.add(2);
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.

Comments

Popular posts from this blog

Installing Bugzilla on Windows

Bugzilla is the Bugs/Issues Tracking Tool from The Mozilla Organization. Version 2.18 is the latest stable release. There are couple of resources which guide a User installing Bugzilla on a Unix/linux machine. However, this entry describes a way to install Bugzilla on a Windows machine (W2K to be precise). This document guides you step by step through the installation process. First, get Administrative access to the machine on which you want to install Bugzilla. It should be a simple step. Usually, Users are given Administrative rights on Windows machine. However, if you dont have, contact your Administrator. Get Bugzilla Then download the Bugzilla from http://bugzilla.org/download.html . There are two ways of gettng it - through CVS or direct downloading the tar file. Remember there are no Zip files. However, any zip utility should be able to untar the Bugzilla. I download the tar file and untarred it using WinZip. I placed the untarred 'bugzilla' directory in my c: drive. So...

Online Hindi Radio Stations

Here is the list of Online Hindi Radio Stations. Copy the URL in your media player and enjoy !! 106.2 HUMFM - UAE ==> http://www.humfm.com/humfm.asx AajKal - Asian Network ==> http://stream.servstream.com/ViewWeb/BBCRadio_music/Event/BBCAsianNetwork_hi.asx Amrit Bani - UK ==> http://62.25.97.192/amritbani?MSWMExt=.asf ApnaRadio - USA ==> http://www.apnaradio.com/live/media24/ApnaRadio.asx Asian Gold Radio - UK ==> http://62.25.96.7/asiangold Asian Sound Radio - UK ==> http://www.vtuner.com/vtunerweb/mms/mms15278.asx BBC News ==> http://www.bbc.co.uk/worldservice/meta/tx/nb/live_news_au_nb.asx BombayBeats FM ==> http://www.1.fm/player/energybbfm32k.asx City 101.6 FM - Dubai ==> http://asx.abacast.com/arabian_radio-city-24.asx DDLive Video - India ==> http://164.100.51.209/ddlive?MSWMExt=.asf DesiSoundz - India ==> http://desisoundz.com:8000 Haagstad Radio - Holand ==> mms://81.205.146.32:21/haagstadradio kismatradio.com ==> http://www.kismatradio....

What are the different type of JDBC drivers?

There are four types of JDBC database driver: The JDBC/ODBC bridge driver (Type 1) A piece of native C-code that translates a JDBC call to an ODBC call. Use this driver for development, not for industrial-strength application environments. Note that you have to have an ODBC database driver manager + an ODBC database driver installed on the server in addition to the JDBC/ODBC bridge. Though useful for learning JDBC and quick testing, bridging solutions are rarely appropriate for production environments. Native API partly java driver (Type 2) A piece of native C-code that translates a java JDBC call to a native database call level API. Use this driver for development and deployment. Due to its native code, this driver can only be used by Java Applications with full computer access (i.e. not Applets). Type 2 drivers generally provide the best performance, but they require the installation of native libraries on clients that need to access the database. Applications using Type 2 drivers ...