Alex Rivera | Logout

adding to empty list

Asked 2011-11-30T11:51:29.340
11

So I have an empty list like so

List<Node> nodes = null;

and then I want to add "Node"s into it

    try {
        File file = new File("test.txt");
        Scanner scanner = new Scanner(file);
        while (true){

            String first= scanner.next();
            if (first.equals("-1")){
                break;
            }
            Node node1= new Node(first, first);
            if (nodes==null){
                nodes.add(node1);
            }
            if (nodes!=null){
                if(nodes.contains(node1)){
                    nodes.add(node1);

                }
            }

So obviously doing .contains in a null list gives me an exception error, but why does doing

    if (nodes==null){
    nodes.add(node1);
}

also gives me a null pointer error? It seems like empty lists are immutable. How can I still keep a List structure and still build it up from empty?

Edit
Report

1 Answer

0
nodes = new ArrayList<Node>();

Initializing it to a new object(empty) should help.

answered 2011-11-30T11:53:40.727

Your Answer