0

二分探索法を使用して、ソートされた辞書の remove メソッドを作成しようとしています。私の辞書は、位置リストのシーケンスベースの辞書です。検索方法は次のとおりです。

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 に答える