Re: pass-by-reference
Niklas Matthies wrote On 11/02/06 14:52,:
On 2006-11-02 13:33, Chris Uppal wrote:
:
For Mark: consider -- an empty tree is still a tree (just as an
empty set is a set, or an empty array is an array). You should be
able to ask it how many elements it contains, and so on. You can't
do that if you have represented it by null. What is, perhaps, even
worse than the logical oddness, is that your code which uses such
trees will be cluttered with endless null-tests:
if (tree == null)
...
else
...
<shudder/>
Well, but with an empty-tree instance his code will likely be
cluttered with:
TreeNode root = tree.getRoot();
if (root == null)
...
else
...
It might not be that much of an improvement.
The idea is not to "expose" the root of the tree at
all, but to keep it internal to the Tree implementation.
That is, instead of
TreeNode root = tree.getRoot();
if (root == null)
tree.insertAsRoot(newNode);
else if (newNode.compareTo(root) < 0)
root.insertToLeft(newNode);
else if (newNode.compareTo(root) > 0)
root.insertToRight(newNode);
else
throw new DuplicateTreeNodeException();
.... he makes the insertion operation a method of the Tree
class itself and just writes
tree.insert(newNode);
Other operations that "need" access to the root can
also be written as methods of the Tree class: delete(),
find(), iterator(), preorderIterator(), ...
Now, I'm not saying this will solve everything: he
might want to do something with his Tree that just doesn't
fit well as a method of Tree, and this "something" might
need explicit access to the root, or might need to do an
externally-operated traversal of some kind. If so he'll
need to check for the null root of an empty tree -- but
since he'll need to check for the null descendants of leaf
nodes anyhow, this might not be any extra code.
And besides: When was the last time you needed access
to the root node of a java.util.TreeSet?
--
Eric.Sosman@sun.com