[英]How to add an ArrayList<Integer> to an ArrayList<ArrayList<Integer>> again and again with different elements in ArrayList<Integer>
我在Java中创建了ArrayList的ArrayList。 并且iam将值存储在它们中,如下所示:
import java.util.ArrayList;
class Test {
public static void main(String args[]) {
ArrayList<ArrayList<Integer>> connections = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> currentConnects = new ArrayList<>();
currentConnects.add(7);
currentConnects.add(4);
connections.add(currentConnects);
currentConnects.clear();
currentConnects.add(10);
currentConnects.add(15);
connections.add(currentConnects);
System.out.println(connections);
}
}
我期望输出为:
[[7, 4], [10, 15]]
但输出是:
[[10, 15], [10, 15]]
如何在不使用任何其他额外变量的情况下达到预期的输出?
实际上,您在connections
对象中两次引用同一对象,因此得到的结果是。
代替currentConnects.clear();
尝试currentConnects = new ArrayList<>();
您需要删除currentConnects.clear();。 并创建一个新的ArrayList对象。您的ArrayList对象指向堆中的同一对象。ArrayList ArrayList<ArrayList<Integer>>
两次包含ArrayList的相同引用
导入java.util.ArrayList;
class Test {
public static void main(String args[]) {
ArrayList<ArrayList<Integer>> connections = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> currentConnects = new ArrayList<>();
currentConnects.add(7);
currentConnects.add(4);
connections.add(currentConnects);
currentConnects = new ArrayList<>();
currentConnects.add(10);
currentConnects.add(15);
connections.add(currentConnects);
System.out.println(connections);
}
}
您必须每次都创建新的数组列表。
当您这样做时:
connections.add(currentConnects);
currentConnects.clear();
您首先添加currentConnects的引用,然后清除currentConnects的内容,而不是在创建新的数组列表。 而是:
ArrayList<Integer> currentConnects = new ArrayList<>();
currentConnects.add(7);
currentConnects.add(4);
connections.add(currentConnects);
currentConnects = new ArrayList<>();
currentConnects.add(10);
currentConnects.add(15);
connections.add(currentConnects);
当您调用connections.add(currentConnects);
由于connections
的类型为ArrayList<ArrayList<Integer>>
,实际上是增加了整个ArrayList中连接的参考, 而不是仅仅在ArrayList中本身的整数。
因此,因为您调用connections.add(currentConnects);
两次,有两个对connections
ArrayList的引用,这就是为什么保留在connections
中的整数打印两次的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.