Eric S Eric S - 3 months ago 13
Java Question

How do binary search trees work in Java without pointers?

I'm trying to compare the way a BST is implemented in Java and C++. In Java a Node would look something like

class Node{
int data;
Node left;
Node right;
}


and in C++ it would be :

class Node{
int data;
Node *left;
Node *right;
}


I'm confused as the why the java approach is working. I understand that in C++ left and right are pointers pointing to an area of memory that contains the next Node. In Java I don't really get how everything ends up being connected. Left and right are Nodes themselves, not pointers to nodes, so would each Node object in Java take up the space of 3 nodes (one for itself and 2 for its children)? If anyone could explain what's really going on here in terms of how exactly all the Nodes are being connected and the difference in memory allocations it would be very helpful.

Also, can the same thing be done in C++? Could you just have Node left and Node right instead of pointers? If so, what's the advantage of using pointers in the first place? Thank you!

Answer

In the Java code the class type (left and right) member declarations implicitly declare pointers. There is no special notation for a pointer in Java, because most everything is handled via pointers. These are called pointers in the Java language specification, but they're known to most Java programmers as references.

In your example it's essentially just the syntax that differs between Java and C++, but do note that neither C++ pointers nor C++ references correspond directly to Java pointers.

Also note: You may encounter arguments that Java doesn't have pointers. For some reason that I can't grok (why are they unfamiliar with the specification of their favorite language, and why are they able to ignore e.g. getting NullPointerException on the screen?) some Java programmers will vehemently deny that the language has pointers. This is a mystery, but it can safely be ignored, I think.