0

我正在尝试使用二进制搜索方法编写排序字典的删除方法。我的字典是一个位置列表、基于序列的字典。搜索方法如下:

private Entry<Integer, V> binarySearch(int key, int low, int high) {
    int mid = (high + low) / 2;
    if(low > high){
        return null;
    }
    else if(sortedList.get(mid).getKey() == key){
        return sortedList.get(mid);
    }
    else if(sortedList.get(mid).getKey() > key){
        return binarySearch(key, low, mid-1);
    }
    else{
        return binarySearch(key, mid+1, high);
    }
}

到目前为止,我的代码是:

@Override
public Entry<Integer, V> remove(Entry<Integer, V> e)
        throws InvalidEntryException { 
if(e == null){
    throw new InvalidEntryException("");
}
Entry<Integer, V> entry = binarySearch(e.getKey(), 0, size());
if(entry != e){
    boolean found = false;
    int i = getLocation(entry.getKey());
    while(!found && i < size()-1){
        entry = binarySearch(e.getKey(), i+1, size());
        if(entry == e){
            found = true;
            sortedList.remove(i);
        }
        i++;
    }
}
else{
    sortedList.remove(getLocation(entry.getKey()));
}
if(entry == null){
    throw new InvalidEntryException("");
}
else{
    return entry;
}
}

任何人都可以帮助任何输入吗?我真的不知道该怎么做,我非常沮丧。如果条目与参数是相同的实例,我基本上需要删除。与字典一样,可能有多个条目具有相同的键,但只有当条目与参数的实例相同时,我才需要删除。

谢谢您的帮助。

4

1 回答 1

0

可能有多个条目具有相同的键,但只有当条目与参数的实例相同时,我才需要删除。

您对 java 中实例的相等性感到困惑。您需要覆盖该equals()方法并定义相等性如何在您的对象上运行。有了这个你还需要看看hashcode()

并且您尝试比较的实例永远不能与传递的 param 实例相同。

于 2013-02-11T16:38:49.173 回答