Search code examples
javaarraylistnullpointerexceptionvariable-initialization

NullPointerException when adding node objects to an ArrayList


I'm getting a NullPointerException when I try to run this code. I've assigned Nodes 2,3,and 4 as children nodes to Node1. I tried to create a method that will go through all the children nodes in Node1 and return the list. I'm not sure what I'm doing wrong.

public class TestingArrays2 {

    List<Node> myList1;
    List<Node> myList2;
    List<Node> myList3;
    List<Node> myList4;

    private Node Node1;
    private Node Node2;
    private Node Node3;
    private Node Node4;

    public TestingArrays2() {
        myList1 = new ArrayList<Node>();
        myList2 = new ArrayList<Node>();
        myList3 = new ArrayList<Node>();
        myList4 = new ArrayList<Node>();

        myList1.add(Node2);
        myList1.add(Node3);
        myList1.add(Node4);

        Node1 = new Node("One", myList1);
        Node2 = new Node("Two", myList2);
        Node3 = new Node("Three", myList3);
        Node4 = new Node("Four", myList4);

        List<Node> allNodesArray = nodeArray(Node1);

        for (int i = 0; i < allNodesArray.size(); i++){
            System.out.println(allNodesArray.get(i).label);
        }
    }

    public static void main(String arg[]) {
        TestingArrays2 testArray = new TestingArrays2();
    }

    public List<Node> nodeArray(Node n){
        List<Node> tempList = new ArrayList<Node>();

        for (int i = 0; i < n.children.size(); i++){
            tempList.add(n.children.get(i));
        }

    return tempList;
    }
}

Solution

  • You're not creating your Nodes. See these lines...

    private Node Node1;
    private Node Node2;
    private Node Node3;
    private Node Node4;
    

    These just declare a variable as being able to contain an object of type Node. However, they initially start with a null value - ie they're empty.

    You're then calling these lines...

    myList1.add(Node2);
    myList1.add(Node3);
    myList1.add(Node4);
    

    Which would insert null values into your List, because you're trying to add an object that hasn't been created yet.

    So, you need to change your code so that these lines...

    Node1 = new Node("One", myList1);
    Node2 = new Node("Two", myList2);
    Node3 = new Node("Three", myList3);
    Node4 = new Node("Four", myList4);
    

    appear before you try to myList1.add() them to the list. This will create the Node objects first, which can then be added to your List.

    As @BalusC mentioned in the comments, it is failing on your for loop later in your code, because it is trying to call .label on a null object. Correcting the order as suggested above will correct this, as all the objects in your List will now be Nodes.