开发者

How to fill two-dimensional array using java enhanced loop?

开发者 https://www.devze.com 2022-12-27 08:12 出处:网络
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

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)
    开发者_Go百科    element = '~';


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, '~');


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.


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


The assignment merely alters the local variable element.

0

精彩评论

暂无评论...
验证码 换一张
取 消