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:
Quotefor(int i = 0; i < array.length; i++)
System.out.println(array);
To:
Quotefor(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:
Quotefor(Iterator <String> i = set.iterator(); i.hasNext(); )
System.out.println(i.nextElement());
Can be replaced with:
Quotefor(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):
Quoteimport 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:
Quoteiago@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)
Quote from: MyndFyrex86] link=topic=4644.msg52293#msg52293 date=1138238389]
Hahaha, way for Java to copy C# and Visual Basic! :P
Actually we don't call them iterators in C# 1.x, we called them enumerators. Iterators were a different kind of the same thing added in 2.0. Both used foreach. :P
That's called revenge, for C# stealing everything else :P
Java has both Enumerators and Iterators. You can't foreach() over an Enumerator, though (unless I screwed up when I was testing it).