Java's foreach construct (which is, in code, simply a variation of for()) allows you to loop through each element in an array or iterator in a loop easily. Doing it with an array is simple, you change the code:
for(int i = 0; i < array.length; i++)
System.out.println(array);
To:
for(String str : array)
System.out.println(str);
There isn't a huge difference for arrays. However, the important change is automatically looping over an iterator. This code:
for(Iterator <String> i = set.iterator(); i.hasNext(); )
System.out.println(i.nextElement());
Can be replaced with:
for(String str : set)
System.out.println(str);
(note: the set that we're iterating over has to be the same type as the variable. For example, I did TreeSet<String> set. If I had done TreeSet<Socket> set, I would have used for(Socket sock : set) to iterate over it)
That's a pretty substantial change in the clarity of the code, and I recommend that, if you're targetting Java 1.5, you make use of this contruct.
Here is the source for the full sample program (Test.java):
import java.io.*;
import java.util.*;
public class Test
{
public static void main(String []args)
{
System.out.println("Array:");
demonstrateArray();
System.out.println();
System.out.println("---------");
System.out.println();
System.out.println("Set:");
demonstrateSet();
}
public static void demonstrateArray()
{
String []array = new String[] { "d", "c", "b", "a" };
for(String str : array)
{
System.out.println(str);
}
}
public static void demonstrateSet()
{
TreeSet <String>set = new TreeSet <String>();
set.add("i");
set.add("a");
set.add("g");
set.add("o");
for(String str : set)
{
System.out.println(str);
}
}
}
[/pre]
And the output:
iago@slayer:~/tmp$ javac Test.java
iago@slayer:~/tmp$ java Test
Array:
d
c
b
a
---------
Set:
a
g
i
o
[/tmp]
(Note that the TreeSet sorts the array)