0

I am trying to implement a LinkedList. The methods are functioning perfect on this example:

    LinkedList list = new LinkedList();
    Node newNode = new Node("sarah", 20);
    list.addToBack(newNode);
    System.out.println(list.nodeAt(0).getName());

But not on this example, when I try to use the same method with an array:

    LinkedList[] list = new LinkedList[3];
    Node newNode = new Node("sarah", 20);
    list[1].addToBack(newNode);
    System.out.println(list[1].nodeAt(0).getName());

For the last example I get the following:

    Exception in thread "main" java.lang.NullPointerException
        at Main.main(Main.java:27)

It's the line where addToBack method is called. This is the method:

public void addToBack(Node newNode) throws NullPointerException {
    if (this.head == null){
        this.head = newNode;
        return;
    }
    Node current = this.head;
    while (current.hasNext()){
        current = current.next;
    }
    current.next = newNode;
    ++size;
}

3 Answers3

1

You didn't create the objects. You just created an array of LinkedList s

LinkedList[] lists = new LinkedList[3]; // Just create the array of linked lists

You must add thing like this

 lists[1] = new LinkedList(); // Create the object at index 1 of the array

 ...


 lists[1].addToBack(newNode);
user9335240
  • 1,629
  • 1
  • 5
  • 13
0

When you create your array of LinkedList() objects those indices are all empty. They don't actually contain LinkedLists until you assign them.

list[1] = new LinkedList();
//then you can add objects to it
Node newNode = new Node("sarah", 20);
list[1].addToBack(newNode);
RAZ_Muh_Taz
  • 3,964
  • 1
  • 10
  • 22
0

By writing:

LinkedList[] list = new LinkedList[3];

You say that list will contain 3 LinkedLists, that's it. You declare what type of objects list will contain, but you don't reserve any place in memory for them. You need to initialize this list with LinkedLists to perform any operations on them:

for(int i = 0; i < list.length; i++) {
     list[i] = new LinkedList();
}

Now you can call methods making changes in list contents.

By the way, I strongly suggest not to name your own implementations with names that are contained in official Java packages, as it make lot of additional and unnecessary work to you or others reading your code as at most they expect official java.util.LinkedList when looking at code containing LinkedList.

Przemysław Moskal
  • 3,321
  • 2
  • 8
  • 20