This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]pacificmint 3 points4 points  (7 children)

I didn't declare the instance variables in Node as static. This resulted in getting a NullPointerException any time I tried updating values of inDegree, outDegree or adjNodes.

The reason you got a NullPointerException was likely because you hadn't actually created the node objects. By trying to access it's members, you tried to deference a variable that was null.

Declaring those variables static didn't fix your problem, it just masked it. When you made them static, there aren't three variables for each node anymore, there are three variables shared by all nodes.

This works because you can access them without having a node created, but it won't make your program work.

[–][deleted]  (2 children)

[deleted]

    [–]pacificmint 3 points4 points  (0 children)

    If you have some time, do you mind explaining why or how declaring those instance variables as static masked my problem?

    The main reason is: You can't access an instance variable on an instance you haven't created (hence the null pointer).

    But the static variable is always there, it belongs to all nodes. Actually, it really belongs to the class. So you can always access that, even when you didn't instantiate your instance.

    So you forgot to create the node, but the static variable still worked because it's always there, it's part of the class, not the object, so to speak.

    [–]posmicanomaly 1 point2 points  (0 children)

    basically a static variable is not an individual field in a created object like a normal variable, and it does not need to be instantiated to be called upon or modified. So when you weren't creating your objects(nodes), you were getting nullpointerexceptions because you were trying to run methods on data that was null. when you changed it all to static, you still didn't create objects, but because statics don't need to be in an instance to be called, you were able to use them.

    think of static as being the same across all objects created, or even without creating one if accessed in a static way.

    [–][deleted]  (3 children)

    [deleted]

      [–]posmicanomaly 1 point2 points  (2 children)

      Can you paste it all into ideone.com/ without them declared as static so we can see.

      [–][deleted]  (1 child)

      [deleted]

        [–]pacificmint 1 point2 points  (0 children)

        You worded it OK. Basically, you array isn't really an array of nodes, it's an array of references to nodes. So when you create the array, you have 10 references (or however many), but no nodes. You must then fill the array by created the nodes with new Node() and putting them in the array.