0

I am trying to have 2D Linked List Array as:

private LinkedList<Integer>[] adjLst;

graph(int n){
    noOfNodes = n-1;

    for(int i=0;i<=noOfNodes;i++){
        adjLst[i] = new LinkedList<Integer>();
    }
}

But when i am calling it from my main class as:

graph g =new graph(13);

It is throwing an NullPointerException?

1 Answer 1

8

You've never initialized adjLst, so it still has its default value of null. You need something like:

adjLst = new LinkedList<Integer>[noOfNodes + 1];
for (int i = 0; i <= noOfNodes; i++) {
    adjLst[i] = new LinkedList<Integer>();
}

It's not clear why you're subtracting 1 from n and then going up to and including that value, mind you. I'd find this easier to understand:

// Note: fixed case of class. Please follow Java naming conventions
Graph(int n){
    adjLst = new LinkedList<Integer>[n];
    for (int i = 0; i < n; i++) {
        adjLst[i] = new LinkedList<Integer>();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.