这不是“如何做某事”。问题,而是“为什么我不能那样做”的问题。
显然,我在这里错过了一些重要的东西(我猜是关于引用文献)来理解这个问题,如果有人能向我解释它那就太好了。
我确实找到了以前处理过这个问题的其他帖子,但没有一个解释它。
我想为 int 矩阵的每个元素分配新值。
我有一段这样的代码:
public static void main(String[] args)
{
int[][] tileMatrix = new int[5][5];
System.out.println("New Tile Values:");
for ( int[] tileLine : tileMatrix)
{
for ( int tile : tileLine)
{
tile = (int) (Math.random() * 39);
System.out.print(tile + " ");
}
System.out.println("");
}
System.out.println("Check Values");
for ( int[] tileLine : tileMatrix)
{
for ( int tile : tileLine)
{
System.out.print(tile + " ");
}
System.out.println("");
}
}
这导致了:
新的图 block 值:
22 17 29 20 5
12 13 38 35 19
1 9 10 23 27
24 3 36 3 19
37 4 5 18 26
检查值
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
很明显我不能改变这样的值。我不知道这在 foreach 循环中通常是不可能的,还是我只是做错了。我可以用普通的 for 循环解决我的问题,我知道,但为什么我必须这样做?
最佳答案
增强的for
循环只会获取数组中元素的值并将它们存储在变量中。对于值,这意味着基元的副本或存储在数组中的引用值的副本。如果您为该变量重新分配新值,则只是修改该变量的值,而不是数组中的值。
这解释了为什么这个for
循环不起作用:
for ( int tile : tileLine) {
tile = (int) (Math.random() * 39);
System.out.print(tile + " ");
}
上面的 for
语句的行为如下:
for (int i = 0; i < tileLine.length; i++) {
int tile = tileLine[i];
//you modify the local variable tile, not the element in the array
tile = (int) (Math.random() * 39);
System.out.print(tile + " ");
}
如果要修改数组中的值,应该直接修改数组中的值:
for (int i = 0; i < tileLine.length; i++) {
tileLine[i] = (int) (Math.random() * 39);
System.out.print(tileLine[i] + " ");
}
关于Java:for/forEach遍历int矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23657727/