Author Topic: [Java 1.5] Using foreach  (Read 3959 times)

0 Members and 1 Guest are viewing this topic.

Offline iago

  • Leader
  • Administrator
  • Hero Member
  • *****
  • Posts: 17914
  • Fnord.
    • View Profile
    • SkullSecurity
[Java 1.5] Using foreach
« on: January 25, 2006, 12:03:49 pm »
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:
Quote
for(int i = 0; i < array.length; i++)
    System.out.println(array);

To:
Quote
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:

Quote
for(Iterator <String> i = set.iterator(); i.hasNext(); )
    System.out.println(i.nextElement());

Can be replaced with:

Quote
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):

Quote
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:

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

Offline MyndFyre

  • Boticulator Extraordinaire
  • x86
  • Hero Member
  • *****
  • Posts: 4540
  • The wait is over.
    • View Profile
    • JinxBot :: the evolution in boticulation
Re: [Java 1.5] Using foreach
« Reply #1 on: January 25, 2006, 08:19:49 pm »
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
I have a programming folder, and I have nothing of value there

Running with Code has a new home!

Our species really annoys me.

Offline iago

  • Leader
  • Administrator
  • Hero Member
  • *****
  • Posts: 17914
  • Fnord.
    • View Profile
    • SkullSecurity
Re: [Java 1.5] Using foreach
« Reply #2 on: January 25, 2006, 08:54:18 pm »
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).