I want to create a chained hash table. It need to be a list of linkedlists, the istructions say I should do it as follows:
ArrayList<LinkedList<String>> hashTable
to initialize the table I use this code:
public static ArrayList<LinkedList<String>> createNewTable (){
double tableSize = Math.pow(baseTableSize, initialTableExponent);
for (int i = 0; i < tableSize; i++){
LinkedList<String> row = new LinkedList<String>();
hashTable.add(row);
}
return hashTable;
}
BUT, when I run it in the "main" I get this exception:
Exception in thread "main" java.lang.NullPointerException
what is the problem? is there a better way of doing it?
thanks!
-
2where do you initialize hashTable variable (which is actually ArrayList)? you need to say "new" somewhere before adding elements to it.hovanessyan– hovanessyan2014年04月23日 09:34:32 +00:00Commented Apr 23, 2014 at 9:34
3 Answers 3
This
ArrayList<LinkedList<String>> hashTable;
should be
ArrayList<LinkedList<String>> hashTable = new ArrayList<>();
i.e. you should instanciate hashTable.
Assuming hashTable is a member variable, you can do this in the constructor;
hashTable = new ArrayList<LinkedList<String>>();
You just declared the ArrayList variable named hashTable but you didn't initialize it. Memory will not be allocated at this stage. For Java, if you are talking about primitive types, they have default values assigned by the compiler. For reference types (Collection Framework), they just act as a hook, you need to instantiate the class and assign it to reference variable.
Your code is not wrong if you have written
hashTable = new ArrayList<LinkedList<String>>();
in another line.
OR, you can do this in a single line as well.
ArrayList<LinkedList<String>> hashTable = new ArrayList<>();
Now your code should work.
Explore related questions
See similar questions with these tags.