Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Standard view
Full view
of .
Look up keyword
Like this
0 of .
Results for:
No results containing your search query
P. 1
Using Foreach Loops in J2SE 1

Using Foreach Loops in J2SE 1

Ratings: (0)|Views: 9|Likes:
Published by api-3819971

More info:

Published by: api-3819971 on Oct 18, 2008
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as DOC, PDF, TXT or read online from Scribd
See more
See less





Using Foreach Loops in J2SE 1.5

Like many Java developers you are probably working with the beta for J2SE 1.5. Here
is another new technique to use with the beta. Looping through a collection of objects
and doing something with each object is one of the most common programming
idioms. You've no doubt coded such a loop many times:

List names = new ArrayList();

for (Iterator it = names.iterator(); it.hasNext(); ) {
String name = (String)it.next();

}Instead of using afor loop, you might have used awh ile loop. You might have used

an Enumeration, instead of an Iterator, if you were working with the older Vector class. Or, you might have used afor loop and a counter, accessing each element using the get(int index) method of the List interface.

If you were to use an array, this is how you would typically iterate through each of its
String[] moreNames = { "d", "e", "f" };
for (int i = 0; i < moreNames.length; i++)

It's not difficult to iterate through a collection, but it is a very repetitive operation.
Iteration requires you to type a good amount of characters. Granted, the template
feature of most IDEs will eliminate your need to type so much. But, as you saw, there
are many ways to iterate through a loop.

The existence of several different iteration techniques costs you more time. For each iteration you encounter, you must spend a few extra seconds digesting the iteration form. If it deviates from the form you're used to seeing, you must examine it even closer. Why did the developer choose to code the iteration differently?

It's also easy to make a mistake in coding your iterator. Ever accidentally coded
something like this?

List names = new ArrayList();

for (Iterator it = names.iterator(); it.hasNext(); ) {
String name = (String)it.next();

}I have. In a small section of code, it's easy to spot the error. In a larger section of
code, it's not as easy to spot.
The foreach Loop

Java 1.5 introduces a new way of iterating over a collection of objects. The foreach
loop is also known as the enhanced for loop. It is a new syntactical construct
designed to simplify iteration. The foreach loop should make iteration more
consistent, but only if and when everyone starts using it.

Effective use of the foreach loop depends on using Java 1.5's parameterized types,
also known as generics. So that you can understand the code in this article, I'll
explain how to use parameterized types.

Here is how you might construct and iterate a list of names in Java 1.5:

List<String> names = new ArrayList<String>();

for (String name: names)

There are two important things in this bit of code: first, the use of a generic list, and
second, the use of the new foreach loop.

To construct an object of the parameterized ArrayList type, youbin d the ArrayList to a
class. In the example, you bind the ArrayList to the String class. You also bind the List
reference to the String class. You are now restricted to adding only String objects to
the list. If you insert, for example, a Date object in thenames collection, your code
will not compile. When you retrieve objects from the list, you need not cast. Java
knows that the list contains only String objects. It does the casting for you, behind
the scenes.

Once you have stored objects in a parameterized List, you can iterate through them
using the foreach loop:

for (String name: names)
You read this statement as, "for each String name in names." The Java VM executes
the body of the foreach loop once for each object in thena mes collection. Each time
through the loop, Java assigns the next object in turn to a local reference variable
calledname. You must declare this reference variable as a String type--the type to
which you bound thenames collection.

The foreach loop is succinct. There is no need to cast; Java does the cast for you. You
can use thena me reference within the body of the loop as a String reference. You
cannot use thena me reference outside the body of the foreach loop.

Using Foreach with Arrays

You saw how the foreach loop allows you to iterate over collection class types. Sun
also modified Java to allow you to iterate through arrays using foreach. The syntax is
exactly the same:

String[] moreNames = { "d", "e", "f" };
for (String name: moreNames)
Supporting Foreach in Your Own Class

Suppose you are building a Catalog class. A Catalog object collects any number of
Product objects. You store these objects using an ArrayList instance variable defined
in Catalog. Code working with a Catalog object will frequently need to iterate through
the entire list of products, to do something with each object in turn.

Here is how the Catalog class might look:
import java.util.*;

class Catalog {
private List<Product> products = new ArrayList<Product>();
void add(Product product) {

}The Product class includes a method that allows you to discount the price on a

class Product {
private String id;
private String name;
private BigDecimal cost;
Product(String id, String name, BigDecimal cost) {

this.id = id;
this.name = name;
this.cost = cost;

}void discount(BigDecimal percent) {
cost = cost.multiply(new BigDecimal("1.0").subtract(percent));
}public String toString() {
return id + ": " + name + " @ " + cost;
}A (Poor) Solution
To allow client code to work with all products, you could create a method in Catalog
that returned the ArrayList of products:
// don't do this
List<Product> getProducts() {
return products;
}Client code could iterate through the list however they chose. However, returning a
collection to a client is a bad idea. By giving the client your collection, you have

relinquished any control over the contents of that collection. Client code could add or
remove elements to the collection without the knowledge of the Catalog object.
You've also burdened the client with more work than necessary.

The Iterable Interface

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->