繁体   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