Implementation Use: Data Structure Lab Exercise for October/28/2011
To do: Implement a Binary Search Tree
Problem: K[] return of methods preOrder(), inOrder() and postOrder()
Problem Details:
The BST must only have its root as a parameter. The methods above mentioned have been described in an interface given by our professor as the following:
/**
* Returns an array of keys filled according
* to the pre-order traversing in a BST.
*/
public K[] preOrder();
public K[] order();
public K[] postOrder();
I could instantiate the generic array with the following code:
public K[] preOrder() {
if (root == null) { return null; }
ArrayList<K> list = new ArrayList<K>();
preOrderRecursive(root,list);
K[] toReturn = (K[]) Array.newInstance(this.getRoot().getKey().getClass(), list.size());
for (int i = 0; i < list.size(); i++) {
toReturn[i] = list.get(i);
}
return toReturn;
}
But, when i tested the method using a testing class also provided by our professor, i got a nullPointerException, wich i think is referring to the root of the BST, that has been once instantiated, but has been removed at a point in the test, and when it calls the method again, the method returns null, not an empty array as expected by the test:
(...)
tree1 = new BSTImpl<Integer, Integer>();
for (int i = 0; i < SIZE; i++) {
tree1.insert(i, i);
}
tree1.remove(1);
tree1.remove(2);
tree1.remove(3);
tree1.remove(4);
assertArrayEquals(new Integer[]{},tree1.preOrder());
(...)
Knowing that i can’t change the return type nor the parameters of the method, what can i do to avoid this Exception? Can i somehow get the component type and use it to instantiate the empty array (how’d i do this?)?
Any tips to improve my code are also welcome.
Question is: Do you really need an Integer array returned? – I don’t think so.
I assume
assertArrayEquals()does not check the component type of the arrays but rather only compares the contained values.With the code you showed, I’d say anything else would not be possible due to type erasure.
So try to return an
Object[]or whatever super-type applies in your case:return new Object[0];and
return list.toArray();(unchecked casts required, but that should be o.k.)
EDIT:
Ok, so
<K extends Comparable>?In that case use:
return new Comparable[0];and
return (Comparable[])list.toArray(new Comparable[]);