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 🙂
You have not instantiated your
Nodesinside the list.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: –
You need to do this before using your matrix elements..