0

I'm trying to implement a LinkedList with an add method. As you can see, I've created a LinkedList class and initialized it with a nodes attribute that's an ArrayList containing Strings.

The add function should simply take a value and append it to the end of nodes. Instead, I'm getting a NullPointerException.

What am I missing here?

public class LinkedList {
  public static ArrayList<String> nodes;

  public LinkedList() {
    ArrayList<String> nodes = new ArrayList<String>();
    System.out.print(nodes);
  }

  public ArrayList<String> add(String value) {
    nodes.add(value);
    return nodes;
  }


  public static void main(String [] args) throws IOException
  {
    LinkedList list = new LinkedList();
    list.add("B");
  }

}
Dylan Richards
  • 796
  • 3
  • 9
  • 26

1 Answers1

1

You're having 2 variables for the same job. A static nodes variable that is not initialized, hence the NullPointerException. And another local nodes variable inside the class constructor that gets initialized but never used.

To use a single nodes variable in an OOP way follow these 2 steps to fix your issues:

  1. Remove static from public static ArrayList<String> nodes; to have a proper instance variable.

  2. Change ArrayList<String> nodes = new ArrayList<String>(); to nodes = new ArrayList<String>(); to initialize that instance variable

Lars Blumberg
  • 19,326
  • 11
  • 90
  • 127