我想添加 LinkedList<Integer>
(我们称之为列表 A)到 LinkedList<LinkedList<Integer>>
(称之为列表 B)。执行此操作后,我需要更改列表 A 的值并将其再次添加到列表 B,但不更改已存储在列表 B 中的值。
我需要它在包含 LinkedList 的 LinkedList 中存储未知数量的路径。应该添加到列表 B 的 LinkedList 的数量总是不同的,我不能只使用 LinkedList<Integer>
C 复制 A。在大多数情况下,我可能需要列表 B 中的大量列表。
public static void main(String[] args)
{
LinkedList<LinkedList<Integer>> B = new LinkedList<LinkedList<Integer>>();
LinkedList<Integer> A = new LinkedList<Integer>();
// just adding some numbers to List A
A.add(1);
A.add(2);
A.add(3);
// adding list A to list B
B.add(A);
// adding another number to list A
A.add(4);
// this will print out [[1,2,3,4]] now
// I want it to print out [[1,2,3]], even though I changed List A
System.out.println(B);
}
当前结果:
[[1, 2, 3, 4]];
预期结果:
[[1,2,3]]
最佳答案
就我个人而言,我会在添加到外部列表时进行复制。
B.add(new LinkedList<>(A));
这种方式的复制与需要复制的原因相结合:您想要存储列表的当前状态。然后您可以安全地修改原始列表。
关于java - 将 LinkedList 添加到包含 LinkedList 的 LinkedList 并更改添加的 LinkedList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56828713/