Java Reference
In-Depth Information
q = new Point(-7, -14);
System.out.println("q = " + q);
return q;
}
Then we change the call on the method to the
x = change(x)
form:
p = change(p);
With these changes, the program produces the following output:
p = java.awt.Point[x=2,y=8]
q = java.awt.Point[x=-7,y=-14]
now p = java.awt.Point[x=-7,y=-14]
The change that occurs in the method propagates back to the
main
method.
Now let's return to the binary tree
add
method to see how we could apply this
technique there. Currently the
add
method has a return type of
void
:
private void add(IntTreeNode root, int value) {
...
}
We can change it so that the last thing we do in the method is to return the value of
root
, which means we have to change the return type to
IntTreeNode
:
private IntTreeNode add(IntTreeNode root, int value) {
...
return root;
}
Then we change every call on
add
to match the
x = change(x)
form. Recall our
old public method:
public void add(int value) {
add(overallRoot, value);
}
The code now becomes:
public void add(int value) {
overallRoot = add(overallRoot, value);
}
The idea is that we pass the value of
overallRoot
to the
add
method and it
passes back the value of the parameter, which might be the old value or might be a
Search WWH ::
Custom Search