[英]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.