在基元数组中重新分配数组值不会更改数组 [英] Reassigning array values in array of primitives does not change array

查看:56
本文介绍了在基元数组中重新分配数组值不会更改数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 2 个循环来设置 2D 布尔数组的值,如下所示:

I try to set the values of a 2D boolean array with 2 loops like this:

 boolean[][] frame = new boolean[10][4];
    for (boolean[] column : frame)
        for (boolean b : column)
            b = true;

但这似乎不起作用,所有布尔值都是假的,为什么?

But that doesnt seem to work, all booleans remain false, why?

推荐答案

您不能为数组中的对象分配新值,因为原始对象不会被更改.以下代码可以解决问题.

You cannot assign new values to objects in an array, because the original object will not be changed. Following code will do the trick.

boolean[][] frame = new boolean[10][4];
for (boolean[] column : frame)
    for (int i = 0; i < column.length; i++)
        column[i] = true;

稍微解释一下:

数组包含指向布尔值的元素.当您将数组元素之一的值分配给名为 b (for (boolean b : column)) 的变量时,变量 b 指向同一个对象数组中的元素指向.接下来,将变量 b 指向 true.现在, b 将是真的.但是,数组中的元素仍然指向同一个对象.

The array contains elements which point to booleans. When you assign the value of one of the elements of the array to a variable called b (for (boolean b : column)), the variable b points to the same object the element in the array points to. Next, you point the variable b to true. Now, b will be true. However, the element in the array still points to the same object.

我希望现在清楚了.一张图片会让它更容易理解...

I hope this is clear now. An image would make it more understandable...

这篇关于在基元数组中重新分配数组值不会更改数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆