I get an error whenever I try to create a simple edge from a node. Basically, I've created two of my own classes called Node and Edge.
The Node class is as follows:
public class Node {
public String ident;
public int numLinks;
public Edge[] neighbours;
public Node (String ident) {
this.ident = ident;
}
public void setNeighbour (Node start, Node end, int cost, int portNum) {
}
}
And my Edge class is as follows:
public class Edge {
Node start;
Node end;
int cost;
int portNum;
public Edge (Node a, Node b, int cost, int portNum) {
this.start = a;
this.end = b;
this.cost = cost;
this.portNum = portNum;
}
}
In my main class, I create two nodes, namely, the start and the end node. The cost and the port number (port number that both these nodes listen to on), I read from a text file and am saving them into an array list named "linkCostList" and "portNumList".
Now, since each start node can have more than one edge (I'm basically creating a graph), I'm calling the setNeighbour() method in the following way:
for (int i = 0; i < startNode.numLinks; i++) {
nextNode = new Node (String name of node I read from text file)
startNode.setNeighbour (startNode, nextNode, linkCostList.get(i), portNumList.get(i));
}
My setNeighbour method is as follows:
public void setNeighbour (Node start, Node end, int cost, int portNum) {
for (int i = 0; i < start.numLinks; i++) {
neighbours[i] = new Edge (start, end, cost, portNum);
}
}
Whenever I compile it, I get an error of the following sort:
Exception in thread "main" java.lang.NullPointerException
at Node.setNeighbour(Node.java: *line number*)
at Start.startlsr(Start.java: *line number*)
at graph.main(lsr.java: *line number*)
}
I understand that this is a null pointer exception, so, somewhere in that loop, I must be doing something wrong. Could anyone please help me figure it out?
Have you initialzed neighbours
in your Node
class? It looks like the exception is from accessing a null array (neighbours[i]
).
Also It looks like the neighbours
array will grow/shrink dynamically? In this case, instead of using array, consider using ArrayList so you don't have to grow neighbours
yourself.