-2

I'm using an Array of ArrayLists of Integer in Java but it can't run. Every time I get the message "Note: Goal.java uses unchecked or unsafe operations." and "Note: Recompile with -Xlint:unchecked for details." after compile and when I want to run it message "Exception in thread "main" java.lang.NullPointerException" appears.

the code is (All is in main method) :

int v = 8;
ArrayList<Integer>[] adj = new ArrayList[11];
adj[0].add(21);

and the error belongs to the last line. searched a lot but nothing ! plz help, stuck for hours now.

3

2 Answers 2

3

According to the comment section, people are right about the null elements in your array of arraylists. To resolve the NullPointerException you should initialize elements of the array right after its declaration and instantiation.

Here's the modified code below that works:

ArrayList<Integer>[] adj = new ArrayList[11];
for (int i = 0; i < 11; i++)
    adj[i] = new ArrayList<Integer>();
adj[0].add(21);
Sign up to request clarification or add additional context in comments.

Comments

1

You should first initialize all indices of the array:

    int v = 8;
    ArrayList<Integer>[] adj = new ArrayList[11];
    for(int i=0; i<adj.length; i++) {
        adj[i] = new ArrayList<>();
    }
    adj[0].add(21);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.