-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.

Ali Hatami
  • 122
  • 7
  • 2
    You haven't initialised any of the elements of the array. So you have an array of 11 `null` `ArrayList`s... – BeUndead Feb 26 '20 at 17:24
  • 2
    Does this answer your question? [NullPointerException when Creating an Array of objects](https://stackoverflow.com/questions/1922677/nullpointerexception-when-creating-an-array-of-objects) – OH GOD SPIDERS Feb 26 '20 at 17:26
  • 1
    For the NPE, see [NullPointerException when Creating an Array of objects](https://stackoverflow.com/questions/1922677). For the warnings, see [How to create a generic array?](https://stackoverflow.com/q/18581002). – Slaw Feb 26 '20 at 17:27

2 Answers2

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);
Jimmy Yang
  • 317
  • 3
  • 9
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);
mohsenJsh
  • 1,818
  • 2
  • 18
  • 43