java 如何使用java增强循环填充二维数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2636222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:09:12  来源:igfitidea点击:

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

javaarrays

提问by evgeniuz

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

基本上,我正在尝试这个,但这只会让数组充满zeros. 我知道如何用普通for循环填充它,例如

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

回答by bruno conde

Thirlerhas explained why this doesn't work. However, you can use Arrays.fillto help you initialize the arrays:

瑟勒解释了为什么这不起作用。但是,您可以使用Arrays.fill来帮助您初始化数组:

    char[][] array = new char[10][10];
    for (char[] row : array)
        Arrays.fill(row, '~');

回答by codaddict

From the Sun Java Docs:

来自Sun Java 文档

So when should you use the for-each loop?

Any time you can. It really beautifies your code. Unfortunately, you cannotuse 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.

那么什么时候应该使用 for-each 循环呢?

任何时候都可以。它确实美化了您的代码。不幸的是,你不能在任何地方使用它。例如,考虑 expurgate 方法。程序需要访问迭代器才能删除当前元素。for-each 循环隐藏了迭代器,因此您无法调用 remove。因此,for-each 循环不可用于过滤。同样,它不适用于需要在遍历列表或数组时替换元素的循环

回答by Thirler

This is because the elementchar 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).

这是因为elementchar 不是指向数组内部内存位置的指针,它是字符的副本,因此更改它只会更改副本。所以你只能在引用数组和对象(不是简单类型)时使用这种形式。

回答by Marcelo Cantos

The assignment merely alters the local variable element.

赋值只是改变局部变量element