Java Vs. C ++ / C Tree Implementation What Happens Under the Hood

So I was looking through my data structures and I never really understood how implementing Java applications with pointers ends up actually working compared to languages ​​that have pointers.

Trees or lists in Java classes are implemented with a node class, which has other node classes as the elements say left and right nodes if it is a tree.

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

      

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

+3


source to share


3 answers


I find that the confusion on this issue tends to come down to understanding how objects are passed in Java.

With updateNodeData, as shown in the code below, you will be passing a copy of the reference by value as the first argument. Then the node data will be changed (assuming the data is public ).

Likewise, nodeToBeChanged leftNode will now also refer to the same node as in newLeftNode. New node with copied values ​​is not 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 confused is that since it is a copy of the reference that is passed by value, you cannot exchange two nodes like below. You will be replacing copies, not actual links.



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

      

Now let's get back to the original question. If a tree node was to be implemented with a node such as this:

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 space wasting memory. It will just be a long chain of nodes and links.

+3


source


In Java, fields Node

are references. There is no other option, so there is no special character.



+3


source


While java does not explicitly use a pointer, it is completely pointer-oriented. Without a pointer, java doesn't work. In java, the 'this' pointer is explicitly used to access the associated data member with the object.

They are called "reference types". Links point to objects. Basically. It is not possible to "take the address" of a variable. But you can copy the value of the variable into the field of the wrapper object that can be referenced.

+3


source







All Articles