简体   繁体   English

Java LinkedList 默认是浅拷贝还是深拷贝?

[英]Is Java LinkedList Shallow Copy or Deep Copy by default?

I am confused on whether linked list node is shallow copy or deep copy by default.我对链表节点默认是浅拷贝还是深拷贝感到困惑。 For example, when we have following code:例如,当我们有以下代码时:

ListNode left = new ListNode(0);
ListNode temp = left;

temp.next = new ListNode(3);
temp = temp.next;

Will this statement temp = temp.next also change the node left to temp.next as well?这个语句temp = temp.next也会将节点 left 更改为temp.next吗? Why?为什么?

Java is not C++ which will copy the instances which are constructed on stack memory. Java 不是 C++,它会复制在堆栈内存上构造的实例。 So all Java objects are created on heap memory, so there won't happen any copying task.所以所有的Java对象都是在堆内存上创建的,所以不会发生任何复制任务。

I think you are coming from C++, which in C++ the object it was created on stack memory will happen copy when you are passing it as parameters or assigning to other variables except if you created with new keyword.我认为您来自 C++,在 C++ 中,它在堆栈内存上创建的对象将在您将其作为参数传递或分配给其他变量时发生复制,除非您使用new关键字创建。 But the Java objects are usually created on the heap and so there will not happen any copying task.但是 Java 对象通常是在堆上创建的,因此不会发生任何复制任务。 So be relax with Java objects, but be careful with C++ objects (on the stack)所以对 Java 对象要放松,但要小心 C++ 对象(在堆栈上)

It's neither -- there's no copying going on here, and perhaps you are confusing references with copies, as they are two different things.两者都不是——这里没有进行复制,也许您将引用与副本混淆了,因为它们是两种不同的东西。 Each node holds a reference to the next node, if it exists, or to null, if it doesn't.每个节点都持有对下一个节点的引用(如果存在)或 null(如果不存在)。

A "copy" is where you create an entirely new instance of a type, one that copies the state of an existing instance of the same type, shallow if the new instance contains the reference fields that hold the exact same references of the original and deep if the new instance's reference fields contain new instances that have the same state as the original's, .... but nowhere in your question are you creating new copy instances, deep or shallow. “副本”是您创建一个类型的全新实例的地方,该实例复制相同类型的现有实例的状态,如果新实例包含保存与原始和深度完全相同的引用的引用字段,则为浅如果新实例的引用字段包含与原始实例具有相同状态的新实例,....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM