I know that in Java, besides several primitive types, everything is a reference type (of an Object). However, I do not find a simple way to do operations that are usually done by using references in C++. In fact, I think a reference in Java is a bit like a pointer in C++, in that if I assign a variable to another object, the previous object referred by this variable will not be affected. However, in C++, if I have an int a
and I make int& b
the reference of "a", then these two are actually the same thing - the assignment of "b" will change the value of "a".
The reason for my question is that I am writing a BST ADT and I encounter some trouble, which I would solve using references in C++.
For example, I want to implement the add
method:
void add(K key, V val) {
if (this.key.equals(key))
this.val = val;
node child = next(key);
// next is a function to determine the child in the next layer according to the key
if (child != null)
child.add(key, val);
else {
... // FIX THIS
}
}
Now, if I am writing C++, I can let next
return a reference and child
be node& so that I only need to let child = new node(key, val);
and I am done. But here in Java the same statement will only assign child
to another node and the tree will not be affected.