有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java链接列表。get()不返回深度复制?

我有一个关于使用LinkedList.get()操作的问题。据我所知,Java通过引用传递对象,因此如果我有一个名为A的链表,并且我有temp B = A.get(i),那么我会检索一个可以修改的对象B,并且更改会反映在A.get(i)

但是,如果对象B在其中(比如另一个LinkedList对象),我没有得到一个深度副本,对吗?是在本例中我必须为类“temp”创建副本构造函数的解决方案。还是有更好的、内置的方法来做到这一点

谢谢你的帮助


共 (3) 个答案

  1. # 1 楼答案

    它不会返回“深度复制”,因为根本没有复制,至少在对象级别没有。让我解释一下。 当您有一个对象实例时,引用该对象的变量是指向该对象的指针。对象可以由许多变量(指针)引用和修改。遵守以下代码:

    // Let's assume I have a custom object class called Student
    // Here the object is created and s now points to the new Student object
    Student s = new Student();
    
    // Here I create another variable that points to the same object
    Student s2 = s;
    

    这两个变量都指向同一个对象,一个变量对该对象所做的任何更改都将反映在另一个变量中

    这与您的列表示例有关。如果您有一个对象的LinkedList,它实际上是指向对象的指针列表。因此,在列表中调用get(2)将获得对列表中第三个对象的引用。它引用的对象是对象,而不是副本。因此,这个对象中的任何引用、变量、方法等仍然存在

    我希望这能回答你的问题:)

  2. # 2 楼答案

    Java as I understand passes objects by reference..

    不。Java通过值传递所有内容。如果您有引用类型,引用通过值传递。见this question.

    if I have a linked list called A, and I do temp B = A.get(i), I retrieve an object B that I can modify and the changes are reflected in A.get(i).

    如果有引用类型列表get(i)将返回对特定实例的引用。列表中的元素和检索到的引用将引用同一对象。因此,如果您以某种方式更改对象,它将从两个引用中“可见”

    However, if the object B has within it (Say another LinkedList object), I do not get a deep copy correct?

    对。你会得到一份推荐信

    Is the solution that I must create a copy constructor for my class 'temp' in this example. Or is there a better, built-in way to do this?

    如果需要对象的深度副本,则必须自己实现

  3. # 3 楼答案

    Java as I understand passes objects by reference

    否。它按值传递引用。它根本不传递对象[RMI的情况除外。]

    so if I have a linked list called A, and I do temp B = A.get(i), I retrieve an object B

    否。您检索到一个引用B的引用。将其添加到列表中时传递的引用就是同一个B

    that I can modify and the changes are reflected in A.get(i).

    是的,见上文

    However, if the object B has within it (Say another LinkedList object), I do not get a deep copy correct?

    对。就像第一个案例一样。没什么区别

    Is the solution that I must create a copy constructor for my class 'temp' in this example.

    解决方案是什么?自1997年以来,我从未在Java中使用过复制构造函数或clone()方法。你想解决什么问题

    Or is there a better, built-in way to do this?

    做什么