我想创建哈希表,它将从我的数组中获取每个字符串并将其分配给唯一的整数值。我的数组是从文件中读取并分配给这样的数组:
public void readFile() throws Exception{
FileInputStream in = new FileInputStream("words.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
wordsList = new String[getNumberOfLines()];
for (int j = 0; j < wordsList.length; j++){
wordsList[j] = br.readLine();
}
in.close();
}
使用这个数组,我编写了创建哈希表的方法,如下所示:
String currentWord;
private Hashtable <String,Integer> wordsHashTable;
LinesReader lr = new LinesReader();
int i;
String[] listOfWords;
public boolean insertValues() throws Exception{
for (i=0; i<lr.getNumberOfLines();i++){
lr.readFile();
listOfWords = lr.returnsWordList();
currentWord = listOfWords[i];
wordsHashTable.put(currentWord, i+1);
}
return wordsHashTable.isEmpty(); //testing purposes only
}
它在以下行引发 NullPointer 异常: wordsHashTable.put(currentWord, i+1); 我搞砸的任何想法?