Skip to main content

Semantics of enhanced for loop differ

No replies
atehrani
Offline
Joined: 2004-01-14

The semantics of the enhanced for-loop and for-loop differ when it comes to object initialization. Ultimately it makes sense, due to the fact that the enhanced for-loop uses an Iterator, it does not immediately jump out at you (see the code below).

I would prefer (even recommend) a compiler warning to help catch these types of mistakes.

<br />
public class ForEach<br />
{<br />
    public static Object[] initializeArray(Object[] objects)<br />
    {<br />
        for ( int i = 0; i < objects.length; i++ )<br />
        {<br />
            objects[i] = new Object();<br />
        }</p>
<p>        return objects;<br />
    }</p>
<p>    public static Object[] initializeArrayEnhanced(Object[] objects)<br />
    {<br />
        for (Object obj : objects )<br />
        {<br />
            obj = new Object();<br />
        }</p>
<p>        return objects;<br />
    }<br />
}</p>
<p>import org.junit.Test;<br />
import static org.junit.Assert.*;</p>
<p>public class ForEachTest<br />
{<br />
    @Test<br />
    public void testInitializeArray()<br />
    {<br />
        Object[] objects = new Object[5];<br />
        Object[] result = ForEach.initializeArray(objects);<br />
        assertNotNull(result);<br />
        for ( int i = 0; i < result.length; i++ )<br />
        {<br />
            assertNotNull(result[i]);<br />
        }<br />
    }</p>
<p>    @Test<br />
    public void testInitializeArrayEnhanced()<br />
    {<br />
        Object[] objects = new Object[5];<br />
        Object[] result = ForEach.initializeArrayEnhanced(objects);<br />
        assertNotNull(result);<br />
        for ( int i = 0; i < result.length; i++ )<br />
        {<br />
            assertNotNull(result[i]);<br />
        }<br />
    }<br />
}<br />