我想将一个列表(让我们称之为LinkedList<Integer> A)添加到一个LinkedList<LinkedList<Integer>> (称为list B)中。这样做之后,我需要更改列表A的值,并再次将其添加到列表B中,但不更改已存储在列表B中的值。
我需要它在包含LinkedLists的LinkedList中存储未知数量的路径。应该添加到列表B中的链表的数量总是不同的,我不能只使用复制A的LinkedList<Integer> C。在大多数情况下,我可能会在列表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]]发布于 2019-07-22 17:27:35
就我个人而言,我会在添加到外部列表时复制。
B.add(new LinkedList<>(A));通过这种方式,复制与需要复制的原因相结合:您希望存储列表的当前状态。然后,您可以安全地修改原始列表。
发布于 2019-07-01 08:05:08
你可以这样做,
A = new LinkedList<Integer>();
A.add(4);代码为什么会这样,是因为你添加了linkedlist a到 b 的引用,所以你对a所做的任何更改都会在b中反映出来。
发布于 2019-07-01 10:26:31
下面的代码将通过Collections.copy将先前存储在B中的列表的所有内容复制到B中,并允许您自由更改列表A的内容,而不会影响存储在B中的列表的值。
public static void main(String[] args) {
LinkedList<LinkedList<Integer>> B = new LinkedList<LinkedList<Integer>>();
for (int i = 0; i < listsGiven.size(); i++) {
LinkedList<Integer> A = listsGiven.get(i);
successiveCopy(B, A, i);
}
}
static void successiveCopy(LinkedList<LinkedList<Integer>> B, LinkedList<Integer> A, int index) {
if (B.size() == 0) {
B.add(A); return;
}
B.add(Collections.copy(A, B.get(index - 1));
}https://stackoverflow.com/questions/56828713
复制相似问题