Iterating over a collection of objects and performing some action on each object is one of the most common task while programming. There are many different iteration techniques that requires to type a good amount of characters and thus costs you more time. Java 1.5 provides many new features including a new way of iterating over a collection of elements. This new feature is known as for-each loop that can be considered as enhanced for loop. This new syntactical construct has been designed to simplify iteration over a collection of elements. For-each construct is used with generics elegantly that takes care of type safety also.
The syntax of for-each loop is shown here:
for(type vaiable : collection){
Statements; }
and
for (type vaiable: array) {
Statements; }
Effective use of the foreach loop
depends on parameterized types that you are using. Here is the example that
shows the element of the List?s object.
|
List names = new ArrayList(); for (Iterator it
= names.iterator(); it.hasNext(); ) {
String name = (String)it.next();
System.out.println(name.charAt(0)); |
Another example shows the for-each loop using the Array?s object.
|
|
Read more at:
http:/www.roseindia.net/java/java-tips/flow/loops/foreach.shtml
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Java foreach
Post your Comment