3

So I've been reviewing my data structures and I've never understood how the java implementation of things with pointers ends up actually working when compared to languages which have pointers.

Trees or lists in java classes are implemented with a node class which has other node classes as elements say left and right nodes if it's a tree.

public class Node {
    private int data;
    private Node left;
    private Node right;
    ...
}

Does the compiler know to just use pointers or is all this being done by value and I have many different versions of the same value saved from my tree nodes?

Paul Hankin
  • 54,811
  • 11
  • 92
  • 118
Fatlad
  • 324
  • 5
  • 21

3 Answers3

3

In Java the Node fields are references. There is no other option so there no special symbol required.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
3

Although java doesn't explicitly use pointer, it is fully pointer oriented. Without pointer java doesn't work.In java, 'this' pointer is used explicitly to access the data member associate with the object.

They are called "reference types". The references point to objects.Basically. There is no way to "take the address" of a variable. But you can copy the value of the variable into a field of a wrapper object, which then can be pointed to by a reference.

sr01853
  • 6,043
  • 1
  • 19
  • 39
3

I find that confusion in this matter generally boils down to not understanding how objects are passed in Java.

With updateNodeData as demonstrated in the code below, you'll be passing a copy of the reference by value as the first argument. That node's data would then be modified (assuming data is public).

Similarly, nodeToBeChanged's leftNode would also now refer to the same node as that passed in newLeftNode. A new Node with copied values isn't cloned/created.

public void updateNodeData(Node node, int newValue){
    node.data = newValue;
}

public void setLeftNode(Node nodeToBeChanged, Node newLeftNode)
{
  nodeToBeChanged.leftNode = newLeftNode;
}

However, what is often confusing is that because it's a copy of the reference that is passed by value, you cannot do a swap of two Nodes as demonstrated below. You'll be swapping the copies and not the actual references.

public void swap(Node node1, Node node2)
{
  Node tmpNode = node1;     
  arg1 = arg2;
  arg2 = tmpNode;
}

Now to come back to the original question. If a Node tree were to be implemented with a Node such as this one:

public class Node {
    private int data;
    private Node left;
    private Node right;
    ...
}

There WILL NOT be different clones of the same Node all over the place wasting memory. It will just be a long chain of nodes and references.

WLin
  • 1,394
  • 10
  • 14
  • Thanks for the help, this really helped my basic understanding :) As did everyone who commented/contributed thanks !! – Fatlad Jan 29 '13 at 17:41