2012-11-21 214 views
0
import java.util.*; 

class HashingDemo { 
    public static void main(String[] args) { 
     Scanner keyboard = new Scanner(System.in); 

     System.out.print("Please input the size of the hash table: "); 
     int tableSize = keyboard.nextInt(); 

     LinkedListN[] hashTable = new LinkedListN[tableSize]; 

     // this works 
     LinkedListN list = new LinkedListN(); 
     list.addToEnd(50); 
     System.out.println(list); 
     // 

     System.out.print("Enter the number of keys to be hashed: "); 
     int numberOfKeys = keyboard.nextInt(); 

     Random randomGenerator = new Random(); 

     for (int i = 0; i < numberOfKeys; i++) { 
      int randomNumber = randomGenerator.nextInt(10000) + 1; 

      int location = randomNumber % tableSize; 

      hashTable[location].addToEnd(randomNumber); 
     } 
    } 
} 

LinkedListN是一個自定義類,(代碼如下)因爲數組不能很好地處理泛型。這爲什麼不工作?

但每次我運行這個程序,我得到以下錯誤時間:

Please input the size of the hash table: 10 
[email protected] 
Enter the number of keys to be hashed: 20 
Exception in thread "main" java.lang.NullPointerException 
    at HashingDemo.main(HashingDemo.java:30) 

即使如我上面評論說,如果我只是有一個LinkedListN和數據添加到它,就沒有問題。這是怎麼回事?我試過並試圖弄清楚,但是我做不到。

回答

3

LinkedListN[] hashTable = new LinkedListN[tableSize];只是分配數組,而不是它內部的對象。爲了克服你必須分配對象爲每個元素的NullPointerException

for (int i = 0; i < numberOfKeys; i++) { 
    int randomNumber = randomGenerator.nextInt(10000) + 1; 
    int location = randomNumber % tableSize; 
    if(hashTable[location]==null) { 
     hashTable[location] = new LinkedListN(); 
    } 
    hashTable[location].addToEnd(randomNumber); 
} 

你已經錯過了線hashTable[location] = new LinkedListN();

+0

或者,您可以檢查'LinkedListN'是否在循環中初始化(延遲初始化),這可以節省大型稀疏表中的內存。 – Jeff

+0

我想我習慣於使用原語,或者如果我使用字符串的對象被自動設置爲「」。謝謝。 –

+0

@Jeff爲什麼要檢查?它絕對不會在其他地方初始化(在此代碼中至少)。 –

1

更改環路:

for (int i = 0; i < numberOfKeys; i++) { 
    int randomNumber = randomGenerator.nextInt(10000) + 1; 
    int location = randomNumber % tableSize; 

    if(hashTable[location] == null) 
     hashTable[location] = new LinkedListN(); 
    hashTable[location].addToEnd(randomNumber); 
} 

否則hashTable[location]旨意是當你第一次使用它們時爲null。