简体   繁体   中英

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

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 = '~';

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

赋值仅改变局部变量element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM