java - 将 LinkedList 添加到包含 LinkedList 的 LinkedList 并更改添加的 LinkedList

标签 java list linked-list

我想添加 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/

相关文章:

java - 更改 Eclipse 窗口生成器下的 Java 程序图标

java - 字符串等于和 == 与字符串连接

c++ - 链接列表数组(使用散列)

java - 来自 Map<T,K> 和 Map<T,V> 的跨映射 : Map<K, V> 的通用键控

Java反射 'Can not set'错误

java - Tapestry 循环遍历 tml 文件中的嵌套 map

javascript - 如何存储功能链的数据?

Python:将全局对象声明为实例变量

python - Python 中的双向链表

c - 标记头引用到链表的尾