Don't you think that this is a drawback of Java?
No. Because:
- There are few cases where you really need it.
- There are workarounds (see below).
- Implementing pass by reference in Java would be difficult. It makes code generation and garbage collection significantly more complicated.
(OK ... so really these are counter-arguments. But we are talking about a language design issue here, and any rational discussion of language designs has to weigh up the pros and cons of supporting a particular feature. And that includes implementation cost and performance issues.)
How could such problems be solved in Java?
The general approach is to restructure your code so that the variable you need to update in the called method is replaced with a reference to a mutable object or an array. This may entail the caller doing a bit more work, but that is generally acceptable.
Alternatively (and in your example) restructure the code so that call by reference is unnecessary.
In your example, there are two observations to make:
The "call-by-reference" mechanism is only used in the case where the tree is empty. It is not difficult to change this so that it is not necessary.
In fact, your use of call-by-reference, and in fact the entire insert
method, is a leaky abstraction. There is nothing to stop you calling the method with a node
object that is nothing to do with the current BinaryTree instance. You are relying on the caller to maintain the (implied) invariants of the tree.
The following version addresses both of these issues:
public class BinaryTree {
private static class TreeNode { ... }
public TreeNode root;
public BinaryTree(){
root = null;
}
public void insert(int x) {
root = insert(root, x);
}
private TreeNode insert (TreeNode node, int x) {
if (node == null) {
return new TreeNode(x);
}
if (node.key > x)
node.left = insert(node.left, x);
else if (node.key < x)
node.right = insert(node.right, x);
return node;
}
}
(I don't exactly like the way that we reassign the left / right pointers at each level after the insertion, but it does make the insertion logic simple.)