tags:

views:

464

answers:

4

Basically, I am trying this, but this only leaves array filled with zeros. I know how to fill it with normal for loop such as

for (int i = 0; i < array.length; i++)

but why is my variant is not working? Any help would be appreciated.

char[][] array = new char[x][y];
for (char[] row : array)
    for (char element : row)
        element = '~';
+3  A: 

This is because the element char is not a pointer to the memory location inside the array, it is a copy of the character, so changing it will only change the copy. So you can only use this form when referring to arrays and objects (not simple types).

Thirler
A: 

The assignment merely alters the local variable element.

Marcelo Cantos
+5  A: 

From the Sun Java Docs:

So when should you use the for-each loop?

Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it.

codaddict
So, with iterator it would work? Thank you for answer.
Shark
@Shark: arrays don't provide an iterator (unless you wrap them using `Arrays.asList()`), but a normal old-school for-loop works just fine.
Joachim Sauer
+5  A: 

Thirler has explained why this doesn't work. However, you can use Arrays.fill to help you initialize the arrays:

    char[][] array = new char[10][10];
    for (char[] row : array)
        Arrays.fill(row, '~');
bruno conde
Thank you for the hint :)
Shark