我有一堆数组。我还有一个数组,我将其插入堆栈、修改并再次插入。每当我更改数组的值时,堆栈中的所有变量都会以相同的方式修改。例如:
int[] array = {1, 1};
Stack<int[]> stack = new Stack<int[]>();
stack.push(array);
array = {1, 3};
stack.push(array);
堆栈应该是 {{1, 1}, {1, 3}}
但实际上是 {{1, 3}, {1, 3}}
。我尝试过 stack.push({1, 3});
但这会导致错误。我也不能每次都声明一个新数组,因为这整个事情是在循环中发生的。
最佳答案
您的代码无法编译。我们忽略不编译和解释java的部分。
I also can't declare a new array every time because this whole thing is happening in a loop.
诺诺。你可以。 int[]
是对象类型(与原始类型相反)。这意味着该变量实际上代表的是藏宝图,而不是宝藏。那么,让我们来分解一下:
int[] 数组 = {1, 1};
这只是语法糖:
int[] array = new int[] {1, 1};
这只是语法糖:
int[] array = new int[2];
array[0] = 1;
array[1] = 1;
此外,new int[2]
命令会创建新的宝藏并将其埋在沙子中,int[] array
部分会创建一个新的藏宝图,并且=
在中间在 map 上画了一个漂亮的 X 标记。 []
和 .
是 Java 语言,意思是:走到 X 处并向下挖掘。 =
在java中的意思是:拿一 block 橡皮擦掉那个X,然后把它放在其他地方。
此外,在 java 中,每当您将东西传递给方法时,它总是副本(但是, map 的副本,而不是宝藏的副本)。
这种思考方式正是 Java 内存模型的工作原理,并且永远不会引导您错误。因此:
int[] array = {1, 1};
// 1 treasure chest made.
// 1 treasure map made. The map is called `array`.
// X marked on the map.
stack.push(array);
// Take your `stack` map, walk to the X. Dig down.
// Open the chest you find here, and yell into it: "push".
// Make a copy of your `array` map, and hand it over.
array = {1, 3};
// This isn't legal java.
array[1] = 3;
// This takes your array map, follows the X,
// digs, tosses out the second element you find
// in the box, and then puts a 3 in there instead.
当然,堆栈看到的都是相同的 3:只有一个宝藏,而且你们都有一张通往它的 map 。
让我们修复它。请记住,=
会消除 X,而 new
会产生新的宝藏。我们在这里想要 2 个宝藏:一个是 {1, 1}
,另一个是 {1, 3}
。因此,涉及到 new
,并且 =
也很有用。让我们使用它们:
int[] array = {1, 1};
stack.push(array);
array = new int[] {1, 3};
// The above is the syntax for making a new int array.
stack.push(array);
System.out.println(stack);
成功了!现在可以了。
原因 int[] x = {1, 3};
是合法的,但 x = {1, 1};
不合法,这是一个怪癖语言。它在语言规范中。 int[] x = ...
正在声明一个带有初始值设定项的新变量,而 x = ...
是一个赋值表达式。
Java 需要知道您想要创建的数组的类型。当编写int x = { ... }
时,这一点非常明显。当您编写 x = { ... }
时,这一点不太明显,这可能是规范不允许简写的原因。请注意,编写 int[] x = new int[] {1, 3};
也完全没问题; int x[] = {1, 3};
只是方便的简写。
//这需要你的数组映射,跟随 X, //挖掘,扔掉找到的第二个元素 //在框中,然后将 3 放入其中。
关于java - 更改添加到堆栈的变量的值而不更改堆栈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66683764/