[英]Java: Getting an old value after Arraylist.set apply
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>
不知道为什么即使更改了index0的Arraylist元素,a仍将保留原始index0值。
你的清单,你的a
变量都指向一个对象,这是在其他地方的内存(点)。 您的set
调用将对新对象的引用放在列表中的该位置,这对a
指向的对象没有影响。
让我们扔一些ASCII艺术:
set
前:
+------------+ | sortedlist | +------------+ | index 0 |------------>+-----------------+ +------------+ +------->| Position #1 | | +-----------------+ | | <2.0, 5.0, 4.0> | | +-----------------+ +-----------+ | | a |-----+ +-----------+
set
:
+------------+ | sortedlist | +------------+ +-----------------+ | index 0 |------------>| Position #2 | +------------+ +-----------------+ | <2.0, 4.0, 4.0> | +-----------------+ +-----------+ +-----------------+ | a |------------->| Position #1 | +-----------+ +-----------------+ | <2.0, 5.0, 4.0> | +-----------------+
如果希望a
和列表都具有更新的位置,则有两个选择:
更新a
在同一时间更新列表,或
不要在列表中放入新对象; 而是更改现有对象的状态
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.