why does this create a null point exception

public ArrayList<K> keysAsList(){

ArrayList<K> temp =new ArrayList<K>();

MapNode t = root;

if (root !=null)

keysAsList(temp, t);

return temp;

}

privatevoid keysAsList(ArrayList<K> t, MapNode x){

t.add(x.key);

keysAsList(t, x.left);

keysAsList(t, x.right);

}

[709 byte] By [aditya15417a] at [2007-11-27 1:03:10]
# 1

You have a recursive function that invokes itself with x.left and x.right. The first thing you do with the passed in value is to get the key (x.key) but if x.left is null or x.right is null then x.key must produce a NPE.

If I were doing this I would put a guard in the method keysAsList(ArrayList<K> t, MapNode x) like

if (x == null)

return;

then you will not need the if (root != null)

sabre150a at 2007-7-11 23:38:13 > top of Java-index,Java Essentials,Java Programming...