Wednesday, March 30, 2005

Enhanced for Loop

Discussion

EnhancedForStatement =
'for', '(', [VariableModifiers], Type, Identifier, ':', Expression, ')', Statement ;

Enhanced for Loop using Array Type

The following code is what you had to write before.

J2SE 1.4 code:
public class ForLoop {
    public static void main(String[] args) {
        Integer[] integers = {
            new Integer(11), new Integer(28), new Integer(85),                                                                     
            new Integer(37), new Integer(43)
        };

        for (int i = 0; i < integers.length; i++) {
            System.out.println(integers[i].intValue()); // 11 28 85 37 43
        }
    }
}

The following code is what you would write now.

J2SE 1.5 code:
public class EnhancedForLoop {
    public static void main(String[] args) {
        Integer[] integers = { 11, 28, 85, 37, 43 };

        for (int i : integers) {
            System.out.println(i); // 11 28 85 37 43
        }
    }
}

Decompiled Enhanced for Loop

This is basically what the enhanced for loop code does — the code looks pretty much like the old J2SE 1.4 code, however javac does not create separate Integer objects for each value with new Integer(11) Instead, javac use the public static Integer valueOf(int i) { static factory method, so that Integer objects may be cashed and Integer objects with the same value may be reused.

public class Main {
    public static void main(String[] args) {
        Integer[] integers = { 
            Integer.valueOf(11), Integer.valueOf(28), Integer.valueOf(85),
                Integer.valueOf(37), Integer.valueOf(43) 
        };
        
        for (int i = 0; i < integers.length; i++) {
            System.out.println(integers[i].intValue());
        }
    }
}

Enumeration

If you are still trying to write an enhanced for loop using a class that returns an Enumeration instead of an Iterator, I will now put you out of your misery: The enhanced for loop does not work with classes that return Enumeration because such classes does not implement the interface Iterable.

The Expression must be of type Iterable or an array type (JLS3 2005:14.14.2).

This code works:
DefaultMutableTreeNode tree = ...;

for (Enumeration e = tree.postorderEnumeration(); e.hasMoreElements();) {
    System.out.println(e.nextElement()); // do something with the element
}
This code won't work:
DefaultMutableTreeNode tree = ...;

for (DefaultMutableTreeNode element : tree) {
    System.out.println(element);  // do something with the element
}

The above code does not work because the Expression tree is not of type Iterable. It is of the type DefaultMutableTreeNode that does not implement Iterable.

References

Resources

No comments: