hashTable数组中的remove()方法

时间:2014-10-27 20:21:28

标签: java arrays key hashtable

因此,我正在执行此分配,并且由于某种原因,从字典中删除密钥的remove()方法无法正常工作。以下是我的方法:

public boolean find(String key){
    // Returns true if dictionary has the specified key and false otherwise
    OpsCount++;
    int FoundIndex = 0; // have to reset it for each find() call
    int index = MADcomp(key); // get the location of the element we're looking for
    int c = 0; // counter

    while (size > c){
        String e = D[index]; // gets the entry of the location of our element
            if (e == null){
                return false;
            }
            else if (e != AVAILABLE){ // if not a removed element
                if (e.equals(key)){ //if the element in that cell has the same key as the element
                                    //we're looking for
                    FoundIndex = index;
                    return true;
                }       
            }
            ProbesCount++;
            index = (index + 1) % size; // goes to next cell
            System.out.println("new index " + index);
            c++;
    }
    return false; // nothing found

}
public void remove(String key) throws DictionaryException{
    OpsCount++;
    boolean found = find(key); //we're calling the find method and we'll have the indexOfFound
                               //variable updated for this element
    if (found == true){
        D[FoundIndex] = AVAILABLE;
        //System.out.println(D[FoundIndex]);

        n--;
    }
     else{

        throw new DictionaryException("No entry with this key exists.");
     }

}

我的测试方法。

// Test 4: try to delete a nonexistent entry.
// Should throw an exception.
try {
    h.remove("R6C8");
    System.out.println("***Test 4 failed");
} catch (DictionaryException e) {
    System.out.println("   Test 4 succeeded");
}

// Test 5: delete an actual entry.
// Should not throw an exception.
try {
    h.remove( "R3C1");
        if (!h.find("R3C1"))
         System.out.println("   Test 5 succeeded");
        else  System.out.println("***Test 5 failed");
} catch (DictionaryException e) {
    System.out.println("***Test 5 failed");
}

我得到了测试4成功,但是5失败了,程序没有终止。我还检查了R3C1变为AVAILABLE(我把删除的条目放到的数组)。它失败了,因为它再次找到R3C1,即如果我说

if (h.find("R3C1"))
             System.out.println("   Test 5 succeeded");

成功了。 谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

你在这里重新声明foundIndex:

int FoundIndex = 0; // have to reset it for each find() call

从类中隐藏FoundIndex。因此,您的函数永远不会设置remove,

使用的FoundIndex

尝试将该行更改为:

FoundIndex=0;

请参阅: http://blog.sanaulla.info/2008/06/27/shadowing-variables-in-java-demystified/