2014-02-23 44 views
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; 
} 

我想加倍哈希,我很困惑如何做到這一點。我認爲我在正確的軌道上,但這是給NullPointerExceptiontable[index].value=value;試圖雙散列

任何幫助將是偉大的。

+0

'table [0]'的值是什麼? –

回答

0

試想想剪斷了一分鐘:

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

這循環的無限直到table[index]空然後繼續上。根據定義table[index]在到達最後一行時必須爲空,並且在嘗試對其進行解引用時肯定會拋出NullPointerException!

也許你打算這樣?

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

不完全清楚你打算如何得到這樣做之後...!但它修復了你的空指針:)

如果我「糾正」你的代碼到這個,你看到爲什麼在另一個線程的海報說你實際上不是雙重哈希?

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

什麼是解決這個問題的最佳方法? – user3277779

+0

好吧,但我是雙重哈希權嗎? – user3277779

+0

4個小時前你對這個相同的問題得到了很好的回答......不知道還有什麼要補充的。 http://stackoverflow.com/questions/21963881/double-hashing-java? – Affe