• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • 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)
  • 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)

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
	List<character> letters = new ArrayList<character>();
	letters.add('A');
	letters.add('B');
	letters.add('C');

	for(char letter : letters){
		System.out.println(letter);
	}

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

    package tips.eforloop;
    class MyLanguages implements Iterable<string>
    {
        @Override
        public Iterator<string> iterator() {
            return new MyLanguagesIterator(
                "I like C , C++ and Java");
        }
    }

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

    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");
        }
    }

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

    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);
            }
        }
    }

Category: JavaTag: 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.

Previous Post: «java Singleton Design Pattern
Next Post: Externalizable Interface in Java »

Reader Interactions

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.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact