0

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!

asked Apr 23, 2014 at 9:32
1
  • 2
    where do you initialize hashTable variable (which is actually ArrayList)? you need to say "new" somewhere before adding elements to it. Commented Apr 23, 2014 at 9:34

3 Answers 3

5

This

ArrayList<LinkedList<String>> hashTable;

should be

ArrayList<LinkedList<String>> hashTable = new ArrayList<>();

i.e. you should instanciate hashTable.

answered Apr 23, 2014 at 9:35
1

Assuming hashTable is a member variable, you can do this in the constructor;

hashTable = new ArrayList<LinkedList<String>>();

answered Apr 23, 2014 at 9:36
0

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.

answered Jun 4, 2021 at 2:39

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.