Enhanced For-loop is a new syntax for traversing over a collection of objects and it was introduced from Java 5.0. Let us see how Enhanced for-loop operates on user-defined Objects. The following example shows the syntax of using enhanced for-loop on a Collection object,
also read:
[code lang=”java”]
List<character> letters = new ArrayList<character>();
letters.add(‘A’);
letters.add(‘B’);
letters.add(‘C’);
for(char letter : letters){
System.out.println(letter);
}
[/code]
Not only can the enhanced for-loop be operated on a Collection type, but on arrays also. The key to note in Enhanced for loop is the type of expression that it can accept on the right-hand side of the ‘:’ symbol. Right from Java 5.0, there is a new interface called java.lang.Iterable
which defines a single method called Iterator iterator()
. And it seems that the enhanced for-loop can operate on any Iterable objects. From Java 5.0, all the Collection API (like List
, Set
, Map
) implement the new Iterable
interface.
Suppose we have a String ‘I like C , C++ and Java’ from which we wish to extract only the possible programming languages and print them using the new for-loop. Then the following code will just do that. Given below is the definition of the MyLangauges class,
MyLanguages.java
[code lang=”java”]
package tips.eforloop;
class MyLanguages implements Iterable<string>
{
@Override
public Iterator<string> iterator() {
return new MyLanguagesIterator(
"I like C , C++ and Java");
}
}
[/code]
The above class returns a customized Iterator
called MyLanguagesIterator
which does the finding and parsing of the languages from the string "I like C , C++ and Java". Let us have a look on the class definition.
MyLanguagesIterator.java
[code lang=”java”]
package tips.eforloop;
class MyLanguagesIterator implements Iterator<string>
{
private StringTokenizer tokenizer;
private boolean moreTokens;
public MyLanguagesIterator(String str){
tokenizer = new StringTokenizer(str, " ");
moreTokens = tokenizer.hasMoreTokens();
}
@Override
public boolean hasNext() {
return moreTokens;
}
@Override
public String next() {
moreTokens = tokenizer.hasMoreTokens();
if (moreTokens){
while(moreTokens){
String token = tokenizer.nextToken();
if (token.equals("C") || token.equals("C++") ||
token.equals("Java")){
return token;
}else{
continue;
}
}
}
return null;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Method not implemented");
}
}
[/code]
Note that the above class makes use of StringTokenizer
class to break the string and finds the presence of language string like ‘C’, ‘C++’ and ‘Java’. When using an instance of MyLanguagesIterator
in the enhanced for-loop, a call will be made to MyLanguagesIterator.hasNext()
. If this method returns true, then the control is taken back to MyLanguages.next()
to get the element. This process continues until the MyLanguages.next()
method returns false
. The following client program makes use of the above customized Iterator.
UDE For Loop.java
[code lang=”java”]
package tips.eforloop;
import java.util.*;
public class UDEForLoop {
public static void main(String[] args) {
MyLanguages languages = new MyLanguages();
for(String lang : languages){
System.out.println(lang);
}
}
}
[/code]
Leave a Reply