I have a 2d array which is of objects of the Node class. This is the Node class:

public class Node {
private boolean edge;
private int parent;

public Node() {
 edge = false;
    parent = 0;
}

public Node(boolean edge, int parent) {
    this.edge = edge;
    this.parent = parent;
}

public boolean isNode() {
    return edge;
}

public void setNode(boolean node) {
    this.edge = node;
}

public int getParent() {
    return parent;
}

public void setParent(int parent) {
    this.parent = parent;
}
}

And this is my 2d array:

private Node[][] adjMatrix = new Node[x][y];

In a method named addEdge I am trying to set the node at the points i,j in the array to true.

public void addEdge(int i, int j) {
        adjMatrix[i][j].setNode(true);
        adjMatrix[j][i].setNode(true);
}

However I am getting a nullpointerexception on this line and I do not know how to fix it.

adjMatrix[i][j].setNode(true); 

I assume it's a simple answer that I haven't been able to find the answer to because I have been looking for awhile. So any help is appreciated.

Thanks a lot :)

share|improve this question
1  
adjMatrix[i][j] is null => you need, somewhere, to initialise it with a non null value: adjMatrix[i][j] = new Node(...);. – assylias Oct 17 '12 at 16:21
Yes sorry the answer was obvious. I previously had had a 2 dimensional array of booleans and as they are primitive types I did not have to initialize them, when I then changed the array to one of objects I forgot about then having to initialize them :) Thanks for the answers everyone! – DanMc Oct 18 '12 at 16:18

closed as too localized by assylias, AmitD, Vikdor, GrailsGuy, Graviton Oct 18 '12 at 3:17

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, see the FAQ.

2 Answers

up vote 1 down vote accepted

You have not instantiated your Nodes inside the list.

Node[][] adjMatrix = new Node[x][y];

The above statement only initializes your array and does not instantiate the element in it.

You need to terate through the matrix using for loop, and for each element do: -

adjMatrix[i][j] = new Node();

You need to do this before using your matrix elements..

share|improve this answer

The array is initialized to null, you have to allocate instances of Node to fill the array.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.