如何复制 Java 对象而不更改影响复制的原始对象

How to copy Java object without a change to the original affecting the copy

在函数 addStartNode 中,我创建了一个新节点 'temp',其值设置为等于 'head' 的值。然后我将 head 设置为一个新节点,其值不同 'v'.

但是,当我打印 'temp' 和 'head' 的值时,它显示相同的内容。

我已经尝试了很多不同的方法来解决这个问题,包括复制构造函数,但它似乎并没有改变任何东西。

任何帮助都会很棒!

public class DoublyLinkedList {

    private static class Node {

        private static int value;

        Node(int v) {
            value = v;
        }

        int getValue() {
            return value;
        }
    }

    private static Node head;

    void addStartNode(int v) {
        if (head == null) {
            head = new Node(v);
        } else {
            Node temp = new Node(head.getValue());
            PRINT VALUES HERE
            head = new Node(v);
            PRINT VALUES HERE
        }
    }
}

您已在节点 class 中将 value 声明为 static

如果该属性是静态的,则它会被所有 Node 实例共享。

变化:

private static int value;

private int value;

假设您将代码更改为这个:

static class Node {

    private static int nbOfNode = 0;
    private int value;

    Node(int v) {
        nbOfNode++;
        value = v;
    }

    int getValue() {
        return value;
    }

    static int getNbOfNode() {
        return nbOfNode;
    }
}

现在 value 不是静态的,那么每个 Node 实例都会有其正确的值。

另一方面 nbOfNode是静态的那么它会在节点class的所有实例之间共享,因为它是一个class级别的变量。

现在如果你运行这个:

Node n1 = new Node(11);
System.out.println(n1.getValue());
System.out.println(Node.getNbOfNode());
Node n2 = new Node(22);
System.out.println(n2.getValue());
System.out.println(Node.getNbOfNode());

它将产生:

11 - the proper value of the node n1

1 - the incremented shared value

22 - the proper value of the node n2

2 - the second increment of the shared value

在 n2 的实例化期间,构造函数将递增与先前通过 n1 的实例化递增的变量相同的变量