NullPointerException with an array of Node Lists

3

I'm making an array with lists of nodes that I have to organize from another list that contains 200 nodes with a value from 0 to 9 each (value assigned random).
The Nodes must be removed from the Main List and assigned to the corresponding List within the array according to their value.
For example, if when deleting a Node that has an 8 inside, I must assign it to the List in position 8 within the array. That while is to erase and assign the nodes but throws me NullPointerException when calling the addEnd method.

This is the code where I get the error:

while(n > 0){
    Nodo x = myList.deletStart();
    for(int a = 0; a < 10; a++){
        if(a == x.getInfo()){
            arr[a].addEnd(x);
            //arr[a].addEnd(new Nodo(x.getInfo()));
            break;
        }
    }
    myList.mostrar();
    System.out.println();
    n--;
}

I initialize the List in this way:

static Lista[] arr = new Lista[10]; 
    
asked by Jonathan Caleb Gomez Perez 11.09.2016 в 19:02
source

2 answers

1

This error is due to one of these factors (or several), surely if you check it you will see the error:

  • Access a position null or nonexistent.
  • Alter or display attributes of objects in null
  • Do not control the size of a array .

In your case you can not delete first and then assign, since it simply does not exist.

while(n > 0){
    Nodo x = myList.deletStart();
    for(int a = 0; a < 10; a++){
        if(a == x.getInfo()){
            arr[a].addEnd(x);
            //arr[a].addEnd(new Nodo(x.getInfo()));
            break;
        }
    }
    myList.mostrar();
    System.out.println();
    n--;
}

You have to use a third variable eg. aux that contains the element if you want to delete it from the beginning.

    
answered by 11.09.2016 в 21:53
0
static Lista[] arr = new Lista[10]; 

'arr' and you initialized it and created an array of type 'List' but with all its empty (null) positions. So when you do this:     arr [a] .addEnd (x); you try to use the 'addEnd (x)' method of a null object.

What you must do is validate:

if(arr[a] == null) {
    arr[a] = new Lista();
}
else {
    arr[a].addEnd(x);
}

Look at this example in the Eclipse debug where all the elements of the array 'o' are not initialized:

    
answered by 12.09.2016 в 19:14