[英]why does this reference not work?
What I Have: A static ArrayList which stores Integers. 我所拥有的:一个存储整数的静态ArrayList。 I add an Integer via reference to it and then I change the value but the value is not updated. 我通过引用添加一个Integer,然后更改了该值,但该值未更新。
import java.util.ArrayList;
public class Main {
public static final ArrayList<Integer> integers = new ArrayList<>();
public Integer integer;
void addInteger(Integer i){
integers.add(i);
}
public static void main(String[] args) {
Main main = new Main();
main.integer = 3;
integers.add(main.integer);
main.integer = 4;
System.out.println(integers.get(0));
}
}
Output: 3 输出3
Question: Why is the output not 4 ? 问题:为什么输出不是4?
Further Question based on follow ups: What is really stored within the ArrayList ? 基于后续问题的进一步问题: ArrayList中真正存储了什么?
EDIT BASED ON THE ACCTPTED ANSWER: 根据接受的答案进行编辑:
Since integer
is an Integer
(and not an int
) the 3
is autoboxed. 由于integer
是Integer
(而不是int
),因此3
将自动装箱。 The ArrayList
stores actually Integer.valueOf(3)
. ArrayList
实际上存储Integer.valueOf(3)
。
When executing main.integer = 4
you're reassigning the value of main.integer
, but the old reference was already added to the List<Integer>
. 当执行main.integer = 4
您将重新分配main.integer
的值,但是旧的引用已经添加到List<Integer>
。 Here's what happens in the code: 这是代码中发生的事情:
//commented this line
//main.integer = 3;
//this line below is what really happens
main.integer = Integer.valueOf(3);
integers.add(main.integer);
//main.integer = 4;
main.integer = Integer.valueOf(4);
Here's what happens: 这是发生了什么:
3
(and store that reference in main.integer
). 您创建对3
的引用(并将该引用存储在main.integer
)。 integers.add(main.integer)
). 然后,此引用存储在列表中(通过integers.add(main.integer)
)。 The reference to 3
is passed by value, so the reference is copied into the list. 对3
的引用按值传递,因此该引用被复制到列表中。 main.integer
to contain a reference to 4
. 然后,更新main.integer
以包含对4
的引用。 This does not affect what is stored in the list. 这不会影响列表中存储的内容。 Compare this with the following snippet: 将此与以下代码段进行比较:
public AtomicInteger integer;
Main main = new Main();
main.integer = new AtomicInteger(3); // Reference to a mutable object
integers.add(main.integer); // Add reference to list
main.integer.set(4); // Change mutable object
System.out.println(integers.get(0)); // Prints 4
From your current code you only assign the first element of your list a value (3). 从当前代码中,您只为列表的第一个元素分配一个值(3)。 If you are expecting to output 4 you need to do 2 things. 如果期望输出4,则需要做2件事。 First make sure you add a new value to your ArrayList. 首先,请确保将新值添加到ArrayList中。 Add another integers.add(main.integer);
添加另一个integers.add(main.integer);
after you change the value of main.integer. 更改main.integer的值之后。 After you add another element to your ArrayList remember to index the new correct element. 将另一个元素添加到ArrayList后,请记住为新的正确元素建立索引。 ie: System.out.println(integers.get(1));
即: System.out.println(integers.get(1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.