ellangog
ellangog

Reputation: 67

Null Pointer Exception Fix - Lists

  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)

Upvotes: 0

Views: 434

Answers (1)

nalply
nalply

Reputation: 28767

Short answer

Initialize v.neighbors with new ArrayList() in vertices.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 v or neighbors is null during the run of the program. For example vertices.get(from) could return null and v.neighbors won't work. Or neighbors is null, and v.neighbors.add() won't work.

And voilà. You admitted that you set neighbors to null when initializing VertexI.

The solution is: Initialize with new ArrayList() instead of null.

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:

if (v != null && v.neighbors != null) {
    v.neighbors.add(new vertexWeight (to, 1));
}

This means, don't add vertices if v or neighbors are 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().

Upvotes: 2

Related Questions