BinarySearchTree remove method malfunctioning when removing integers

萝らか妹 提交于 2019-12-13 08:03:45

问题


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;
}

回答1:


Is int an object in Java?

int is not considered a object here a question on stackoverflow for proof



来源:https://stackoverflow.com/questions/29452088/binarysearchtree-remove-method-malfunctioning-when-removing-integers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!