简体   繁体   中英

Array into HashTable

I want to create hashtable which would take each String from my array and assign it to unique integer value. My array is read from file and assigned to array like this:

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();
}

Using this array I wrote method to create hash table like this:

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
}

It throws NullPointer exception at line: wordsHashTable.put(currentWord, i+1); Any ideas where I messed up?

You must initialize your wordsHashTable with an instance of the class:

private Hashtable <String,Integer> wordsHashTable = new Hashtable<>();

However , do note that the Hashtable class is obsolete; you should use java.util.HashMap instead.

Initialize your hash table. You forgot to initialize it.

 private Hashtable <String,Integer> wordsHashTable = new Hashtable<>();

You did not initialized the `Hashtable'.

private Hashtable <String,Integer> wordsHashTable = new Hashtable <String,Integer>();

will fix it.

However, I would recommend you to move to something more modern like a HashMap

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM