Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding to empty list

Tags:

java

list

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?

like image 474
sujinge9 Avatar asked Nov 30 '11 11:11

sujinge9


People also ask

How do you append to an empty string in Python?

To append to an empty string in python we have to use “+” operator to append in a empty string.

How do you return an empty list in Python?

In Python, an empty list can be created by just writing square brackets i.e. []. If no arguments are provided in the square brackets [], then it returns an empty list i.e.


1 Answers

List<Node> nodes = null;

This is not an empty list, this is a list reference which is iniitalized to null. You want rather:

List<Node> nodes = new LinkedList<Node>();

or similar. This gives you an empty list.

EDIT: After the change of question, this logic is completely messed up:

Node node1= new Node(first, first);
if (nodes==null){
    nodes.add(node1);
}
if (nodes!=null){
    if(nodes.contains(node1)){
        nodes.add(node1);

    }
}

What you're saying here is that if nodes == null (which it is now not), then try to add the node to the list. If it is not null, and node1 is already in the list (which it is not), then add it to the list. You can replace the lines above with:

if (!nodes.contains(node1)) {
    nodes.add(node1);
}

which says if the node doesn't exist in the list, add it.

like image 53
Matthew Farwell Avatar answered Sep 18 '22 00:09

Matthew Farwell