0
    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 值。

4

1 回答 1

4

您的列表和a变量都引用(指向)内存中其他位置的对象。您的set调用在列表中的该位置引用了一个对象,这对a指向的对象没有影响。

让我们向它扔一些 ASCII-Art:

之前set

+------------+
| 排序列表 |
+------------+             
| 索引 0 |------------>+------------------+
+------------+ +-------->| 位置#1 |
                  | +-----------------+
                  | | <2.0、5.0、4.0> |
                  | +-----------------+
+-----------+ |
| 一个 |-----+
+-----------+

之后set

+------------+
| 排序列表 |
+------------+ +-----------------+
| 索引 0 |------------>| 位置#2 |
+------------+ +-----------------+
                           | <2.0、4.0、4.0> |
                           +-----------------+

+-----------+ +-----------------+
| 一个 |-------------->| 位置#1 |
+-----------+ +-----------------+
                           | <2.0、5.0、4.0> |
                           +-----------------+

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

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

  2. 不要在列表中添加新对象;相反,更改现有对象的状态

于 2013-09-29T14:38:12.917 回答