I wrote the BinaryTree structure from scratch, which included a remove(Object obj) method to remove elements from said tree. It seems to function correctly for every type except an Integer, and I can't figure out why.
public BinaryTree<E> remove(Object obj) {
try{
E value = (E)obj;
int cmp = value.compareTo(this.value);
if(cmp == 0) {
List<BinaryTree<E>> kids = children();
if(kids.size() == 0) {
return new EmptyBinarySearchTree<E>();
}
if(kids.size() == 1) {
return kids.get(0);
}
//2 children
BinaryTree<E> successor = ((BinarySearchTree)right).smallest();
BinaryTree<E> result = remove(successor.getValue());
result.setValue(successor.getValue());
return result;
}
if(cmp < 0) {
left = left.remove(value);
}
if(cmp > 0) {
right = right.remove(value);
}
}
catch(ClassCastException cce) {
}
return this;
}
I'm driving the BinaryTree with the following, which also implements Set that I built:
package setDriver;
import set.*;
import list.*;
public class HwTreeSetDriver
{
public static void main()
{
Set <Integer> values;
values = new TreeSet <Integer> ();
values.add (3);
values.add (5);
values.add (3);
for (int j=0; j<5; j++)
values.add (j * 10);
Iterator<Integer> itty = values.iterator();
while (itty.hasNext())
if (itty.next() % 2 == 1)
itty.remove(); // remove odd numbers
}
}
After running the driver, the size is still 6, and the set contains 3, 5, 10, 20, 30, 40.
The following is the remove(Object obj) method in TreeSet, which in turn calls the remove method I posted initially:
public boolean remove(Object obj){
if(!contains(obj)) return false;
tree = tree.remove(obj);
size--;
return true;
}