2012-10-16 47 views
0

我想用哈希表实现一个字典(不使用Java提供的哈希表类,而是从头开始)。下面是我的Dictionary类的find()方法,用于检测插入/移除时表中是否存在键。如果键已经在表中,则返回与键相关联的分数(表中的元素作为键/分值插入到每个表位置中的LinkedLists中)。如果不是,则返回-1。为什么这个数组给出一个空指针异常?

我正在运行一个提供的测试程序来确定我的Dictionary类是否工作,但在达到某个点时遇到NullPointerException。下面包含的是特定的测试。为什么这个例外会出现? (如果需要,我可以提供更多的代码!)

查找:

public int find(String config) { 
    for (int i = 0; i < dictSize; i++) { 
     if (dict[i] != null) { 
      LinkedList<DictEntry> current = dict[i]; 
      String currentConfig = current.peek().getConfig(); //Dictionary.java:66 

      if (currentConfig.equals(config)) { 
       int currentScore = current.peek().getScore(); 
       return currentScore; 
      } 
     } 
    } 

    return -1; 
} 

插入:

public int insert(DictEntry pair) throws DictionaryException { 
    String entryConfig = pair.getConfig(); 
    int found = find(entryConfig); //Dictionary.java:27 

    if (found != -1) { 
     throw new DictionaryException("Pair already in dictionary."); 
    } 

    int entryPosition = hash(entryConfig); 

    if (dict[entryPosition] == null) { //Dictionary.java:35 
     LinkedList<DictEntry> list = new LinkedList<DictEntry>(); 
     dict[entryPosition] = list; 
     list.add(pair); 
     return 0; 
    } else { 
     LinkedList<DictEntry> list = dict[entryPosition]; 
     list.addLast(pair); 
     return 1; 
    } 
} 

测试:

// Test 7: insert 10000 different values into the Dictionary 
     // NOTE: Dictionary is of size 9901 
    try { 
     for (int i = 0; i < 10000; ++i) { 
      s = (new Integer(i)).toString(); 
      for (int j = 0; j < 5; ++j) s += s; 
      collisions += dict.insert(new DictEntry(s,i)); //TestDict.java:69 
     } 
     System.out.println(" Test 7 succeeded"); 
    } catch (DictionaryException e) { 
     System.out.println("***Test 7 failed"); 
    } 

异常堆栈跟踪:

Exception in thread "main" java.lang.NullPointerException 
    at Dictionary.find(Dictionary.java:66) 
    at Dictionary.insert(Dictionary.java:27) 
    at TestDict.main(TestDict.java:69) 
+1

请张贴您的异常堆栈跟踪。 – sakthisundar

+0

以及帖子插入方法代码 – zaffargachal

+0

什么是'dict'? –

回答

5

peek()返回null,这就是为什么。您可以在调用getConfig()之前进行无效性检查。

+0

检查'if(dict [i]!= null)'不够吗?我应该再次检查'getConfig()'吗? – user41419

+0

替换字符串currentConfig = current.peek()。getConfig();通过DictEntry entry = current.peek(); if(entry!= null){String currentConfig = entry.getConfig(); ...} – Aubin

+0

究竟@Aubin,谢谢。您使用dict [i]进行的检查仅检查该对象是否为空。调用peek()会检查列表的头部,如果列表为空,则为null。 –

相关问题