Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 列表更改列表中的值_Java_List - Fatal编程技术网

Java 列表更改列表中的值

Java 列表更改列表中的值,java,list,Java,List,我对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.

我对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]

tt有一个元素指向t时,我刚刚添加了res。当您修改t时,您也在修改tt的第一个也是唯一一个元素。如您所见,t有两个值:1和2。

这是因为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;
}

tt有一个元素,它是对t的引用,您在其中插入了1和2。有什么解决办法吗?将t添加到tt@SihanWang只要做tt.addnew ArrayList;而是复制一份,得到你想要的。@kiruwka好极了!非常感谢。