【问题标题】:remove() method in hashTable array哈希表数组中的 remove() 方法
【发布时间】:2014-12-23 03:19:38
【问题描述】:

所以我正在做这个作业,由于某种原因,从字典中删除键的 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");

成功了。 感谢您的帮助!

【问题讨论】:

    标签: java arrays key hashtable


    【解决方案1】:

    你在这里重新声明 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/

    【讨论】:

    • 谢谢!!花了这么多时间试图找到错误大声笑
    猜你喜欢
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 2010-10-29
    • 2011-07-23
    • 2011-08-22
    相关资源
    最近更新 更多