0
public class HashTable <K, V> implements Table<K, V>{
    PairHolder table[];
    int idx;
    public HashTable(int size){
        table=new PairHolder[size];
    }   
    public void put(K key, V value) {
        int hVal = key.hashCode();  
        int index = hashFunc1(hVal);
        int temp = hashFunc2(hVal);
        int col = index +=temp;

        while(table[index]!=null){
            index += temp;
            index %=table.length;
        }
        table[index].value=value;

    }
}
public int hashFunc1(int key){
    int abs = Math.abs(key%table.length);
    return abs;
}

public int hashFunc2(int key){
    int abs = Math.abs(5-key%5);
    return abs;
}

I am trying to double hash and I am confused on how to do it. I think I am on the right track but this is giving a NullPointerException on table[index].value=value;.

Any help would be great.

4

1 回答 1

0

想一想这个片段:

while(table[index]!=null){
    index += temp;
    index %=table.length;
}
table[index].value=value;

无限循环,直到table[index] 空,然后继续。根据定义table[index],当您到达最后一行时必须为 null,并且当您尝试取消引用它时肯定会抛出 NullPointerException!

也许你打算这样?

while(table[index]!=null){
    index += temp;
    index %=table.length;
}
table[index] = new PairHolder(key,value);

不完全清楚你打算如何实现 get 之后......!但它修复了你的空指针:)

如果我对此“更正”您的代码,您是否明白为什么另一个线程中的海报说您实际上不是双重哈希?

public void put(K key, V value) {
    int keyInt = key.hashCode();  
    int hash1 = hashFunc1(keyInt);
    int hash2 = hashFunc2(keyInt);

    int index = hash1 % table.lenght;
    int temp = hash2;
    //etc etc
}

public int hashFunc1(int key){
    int abs = Math.abs(key);
    return abs;
}

public int hashFunc2(int key){
    int abs = Math.abs(5-key%5);
    return abs;
}
于 2014-02-23T07:45:01.460 回答