public void createGraph () {
int oldFrom = -1;
int oldTo = -1;
for(int i = 0; i < edges.size(); i++) {
EdgeI e = edges.get(i);
int from = e.from;
int to = e.to;
VertexI v = vertices.get(from);
if (from == oldFrom && to == oldTo){
vertexWeight wic = v.neighbors.get(v.neighbors.size() - 1);
wic.w++;
}
else {
v.neighbors.add(new vertexWeight (to, 1));
oldFrom = from;
oldTo = to;
}
}
}
neighbors is a public List from VertexI class. w is a public integer from vertexWeight class. edges is a list located in my main class. I keep getting a null pointer exception for this line of code:
v.neighbors.add(new vertexWeight (to, 1));
Tried working on it for around 15 minutes and I didn’t get it to work. What am I messing up on?
java.lang.NullPointerException
at tester.createGraph(tester.java:60)
at tester.main(tester.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Short answer
Initialize
v.neighborswithnew ArrayList()invertices.get().Long answer
Your question omitted a crucial information: How you initialized
neighbors. Why is this important?See: What is a NullPointerException, and how do I fix it?
In your case I guessed that either
vorneighborsis null during the run of the program. For examplevertices.get(from)could return null andv.neighborswon’t work. Orneighborsis null, andv.neighbors.add()won’t work.And voilà. You admitted that you set
neighborsto null when initializingVertexI.The solution is: Initialize with
new ArrayList()instead ofnull.If that would not have been possible or you cannot avoid null pointers for some other reason, you can do null pointer checks like this:
This means, don’t add vertices if
vorneighborsare null.But this is complicated and error-prone. It is easier to avoid null pointers as much as possible. Some would say, avoid them at all costs! Throw an exception instead or return an “empty” object like
new ArrayList().