numberjak
numberjak

Reputation: 1255

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

In the function addStartNode, I create a new Node 'temp' whose value is set to equal that of 'head'. Then I set head to be a new Node with value different 'v'.

However, when I print both the values for 'temp' and 'head', it displays the same thing.

I've tried many different approaches to this, including a copy constructor, but it doesn't seem to be changing anything.

Any help would be great!

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
        }
    }
}

Upvotes: 1

Views: 1411

Answers (1)

Guillaume Barré
Guillaume Barré

Reputation: 4228

You have declared value as static in the Node class.

If the attribute is static then it is shared by all instances of Node.

Change :

private static int value;

To

private int value;

Imagine you change your code to this one :

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;
    }
}

Now value is not static then each instance of Node will have its proper value.

On the other hand nbOfNode is static then it will be shared among all the instances of the Node class, because it is a class level variable.

Now if you run this:

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());

It will produce :

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

During the instantiation of n2 the constructor will increment the same variable than the one previously incremented by the instantiation of n1

Upvotes: 3

Related Questions