将LinkedList添加到包含LinkedList的LinkedList中,并更改添加的LinkedList

时间:2019-06-30 23:27:51

标签: java list linked-list

我想将一个LinkedList(称为列表A)添加到LinkedList>(将其称为列表B)。这样做之后,我需要更改列表A的值,然后再次将其添加到列表B中,但又不更改已存储在列表B中的值。我需要这样做,以在包含LinkedList的LinkedList中存储未知数量的路径。应该添加到列表B的LinkedList的数量始终是不同的,我不能只使用复制A的LinkedListC。在大多数情况下,我可能会在列表中需要很多列表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]]

3 个答案:

答案 0 :(得分:0)

您可以这样做,

 A = new LinkedList<Integer>();
 A.add(4);

其行为的代码是将链接列表 a 的引用添加到 b ,因此您对 a 所做的任何更改都会反映在b。

答案 1 :(得分:0)

以下代码将通过Collections.copy将存储在先前列表中的所有内容复制到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));
}

答案 2 :(得分:0)

我个人而言,添加到外部列表时会复制。

B.add(new LinkedList<>(A));

通过这种方式,复制与需要复制的原因结合在一起:您要存储列表的当前状态。然后,您可以安全地修改原始列表。

相关问题