简体   繁体   中英

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);
        }

the catlog will show

[<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>

Don't know why even after Arraylist element of index0 changed, the a will still remain the original index0 value.

Your list and your a variable both refer (point) to an object, which is elsewhere in memory. Your set call puts a reference to a new object at that position in the list, which has no effect on the object that a is pointing to.

Let's throw some ASCII-Art at it:

Before set :

+------------+
| sortedlist |
+------------+             
| index 0    |------------>+-----------------+
+------------+    +------->|  Position #1    |
                  |        +-----------------+
                  |        | <2.0, 5.0, 4.0> |
                  |        +-----------------+
+-----------+     |
|     a     |-----+
+-----------+

After set :

+------------+
| sortedlist |
+------------+             +-----------------+
| index 0    |------------>|  Position #2    |
+------------+             +-----------------+
                           | <2.0, 4.0, 4.0> |
                           +-----------------+

+-----------+              +-----------------+
|     a     |------------->|  Position #1    |
+-----------+              +-----------------+
                           | <2.0, 5.0, 4.0> |
                           +-----------------+

If you want both a and the list to have an updated position, you have two choices:

  1. Update a at the same time you update the list, or

  2. Don't put a new object in the list; instead, change the state of the existing object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM