JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Enhanced for-loop for User-defined objects

August 21, 2007 by Krishna Srinivasan Leave a Comment

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:

  • New Features in Java 5.0
  • Generics in Java 5.0
  • Annotations in Java 5.0

[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(&quot;Java&quot;)){
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]

Filed Under: Java Tagged With: Java 5.0

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved