gpt4 book ai didi

Java:在 Arraylist.set 应用后获取旧值

转载 作者:行者123 更新时间:2023-12-01 18:43:06 24 4
gpt4 key购买 nike

    int count=0    
Position a = sortedlist.get(count);
if(...)
{
System.out.println(sortedlist);
//change the arraylist index(count) here
sortedlist.set(count, new Position(a.start(),sortedlist.get(i).start(),a.height()));
System.out.println(sortedlist);
//print out position a, prospected changed value
System.out.println(a);
}

目录将显示

[<2.0, 5.0, 4.0>, <4.0, 7.0, 3.0>, <1.0, 3.0, 2.0>, <2.0, 4.0, 1.0>]
[<2.0, 4.0, 4.0>, <4.0, 7.0, 3.0>, <1.0, 3.0, 2.0>, <2.0, 4.0, 1.0>]
<2.0, 5.0, 4.0>

不知道为什么Arraylist的index0元素改变后,a仍然保持原来的index0值。

最佳答案

您的列表和a变量都引用(指向)位于内存中其他位置的对象。您的 set 调用将对列表中该位置的 new 对象进行引用,这对 a 指向的对象没有影响.

让我们添加一些 ASCII 艺术:

设置之前:

+------------+| sortedlist |+------------+             | index 0    |------------>+-----------------++------------+    +------->|  Position #1    |                  |        +-----------------+                  |        | <2.0, 5.0, 4.0> |                  |        +-----------------++-----------+     ||     a     |-----++-----------+

设置后:

+------------+| sortedlist |+------------+             +-----------------+| index 0    |------------>|  Position #2    |+------------+             +-----------------+                           | <2.0, 4.0, 4.0> |                           +-----------------++-----------+              +-----------------+|     a     |------------->|  Position #1    |+-----------+              +-----------------+                           | <2.0, 5.0, 4.0> |                           +-----------------+

如果您希望 a 和列表都有更新的位置,您有两种选择:

  1. 更新列表的同时更新a,或者

  2. 不要将对象放入列表中;相反,更改现有对象的状态

关于Java:在 Arraylist.set 应用后获取旧值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19079255/

24 4 0