0

I have to write a hashtable that uses chaining in the array index to store multiple values in the same place place rather than linear probing. However my array of linked lists seems to instance full of nulls in this test but I get a NullPointerException when I try to call linked list methods. Neither me nor my professor can seem to figure out why.

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

import Hash.*;
import LinkedList.*;

public class Main {

    public static void main(String[] args) {
LList<Integer>[] testArray = (LList<Integer>[]) new LList<?>[5];
        for(int i=0;i<5;i++)
            System.out.println(testArray[i]);

        System.out.println(testArray[0]);
        System.out.println(testArray[0].size());
        testArray[0].add(40);
        }
    }

Then the Linked List class package LinkedList;

public class LList<T> implements I_LList<T> {
    protected int numElements;
    protected boolean found;

    protected LLNode<T> current;
    protected LLNode<T> previous;
    protected LLNode<T> list;

    public LList(){
        list = null;
        current = null;
        numElements = 0;
    }
    public void add(T element){
        System.out.println("LList add()");
        LLNode<T> newNode = new LLNode<T>(element);
        newNode.setLink(list);
        list = newNode;
        numElements++;
    }
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • Please post the stack trace. – Turing85 Apr 21 '15 at 22:00
  • 3
    Arrays of object references are initialized with `null` elements. You have to initialize every element manually, like in a `for` loop. – Luiggi Mendoza Apr 21 '15 at 22:00
  • *"my array of linked lists seems to instance full of nulls in this test but I get a NullPointerException when I try to call linked list methods"* What don't you understand exactly? What do you think `null` means? http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it – Radiodef Apr 21 '15 at 22:09
  • Thanks guys! yea I got it working by making a shell list as Java and Luiggi suggested needed to be done so each LList is generated when the table is made now. – Jordan Brunette Apr 22 '15 at 18:20

1 Answers1

1

You instantiate the array of LList objects but don't instantiate each LList object.

LList<Integer>[] testArray = (LList<Integer>[]) new LList<?>[5];
for(int i=0;i<5;i++)
{
    testArray[i] = new LList<Integer>(); // add this line
    System.out.println(testArray[i]);
}

Your NullPointerException came from the line System.out.println(testArray[0].size()); as you are trying to call the size() of a null object.

Java Devil
  • 10,629
  • 7
  • 33
  • 48