0

I am trying to create a java class to implement wheighted graphs. But I get the NullPointerException error in nodes.add(a) of the constructor.

public class WGraph {
public ArrayList<Node> nodes;

public WGraph(int n) {
    int i;
    for(i=0; i<=n; i++) {
        Node a = new Node(i);
        nodes.add(a);
    }

}

The class Node and in particular the Node(int key) constructor are defined as follows:

public class Node {
public int key;
public ArrayList<Edges> connections;


public Node(int key) {
    this.key=key;
    this.connections = new ArrayList<Edges>();

When I run

WGraph o = new WGraph(3);


System.out.println(o);

I get the NullPointerException error and I have no ideia why.

0 Answers0