我对 java 列表感到困惑:
public static void testListValueChange() {
List<Integer> t = new ArrayList<>();
List<List<Integer>> tt = new ArrayList<List<Integer>>();
int a = 1;
t.add(a);
tt.add(t);
System.out.println(tt);
t.add(2);
System.out.println(tt);
}
为什么我的第二次打印打印出[[1,2]]
?我刚刚在 res = [1] 时添加了 res
最佳答案
这是因为 List.add
确实添加了一个指向对象的指针(引用),并且不会复制该对象然后添加副本。这是 Java 中处理对象时的正常行为,当您使用基元时情况有所不同(这里它将处理副本,而不是指针/引用)。
在这里您可以看到相同的行为:
public class MyClass {
int a;
}
public void a() {
MyClass x = new MyClass(); // "x" is an object
x.a = 1;
b(x); // <- it calls method "b" with a reference/pointer to "MyClass x"
System.out.println(x.a); // <- prints 2
}
public void b(MyClass x) {
x.a = 2;
}
以及原语:
public void a() {
int x = 1; // "x" is a primitive
b(x); // <- it calls method "b" with a copy of "int x"
System.out.println(x); // <- prints 1
}
public void b(int x) {
x = 2;
}
关于java - 列表更改列表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26822651/