【问题标题】:remove method sorted dictionary java删除方法排序字典java
【发布时间】:2013-02-12 00:38:49
【问题描述】:

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

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

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

感谢您的帮助。

【问题讨论】:

    标签: java dictionary


    【解决方案1】:

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

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

    您尝试比较的实例永远不能与传递的参数相同。

    【讨论】:

    • 不,我明白。我不想覆盖 equals 方法。我被指示使用 == 运算符不更改 equals()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    • 2021-09-02
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多