簡體   English   中英

Java:應用Arraylist.set之后獲取舊值

[英]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和列表都具有更新的位置,則有兩個選擇:

  1. 更新a在同一時間更新列表,或

  2. 不要在列表中放入對象; 而是更改現有對象的狀態

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM