-2

I'm getting a null pointer exception on the following code (part of a larger program - the exception is thrown on the line where "add" is called).

public class A
{
    static ArrayList<Integer> sets[];
    public static void main(String[] args)
    {
         sets = new ArrayList[5];
         sets[0].add(1);
    }
}

I also do not understand why the compiler is requiring me to make any class level variables static (e.g. the ArrayList). As far as I can tell, these things shouldn't be in a static context (in terms of coding practice, not compiler problems) and yet the compiler is requiring it.

Thanks in advance.

gmaster
  • 692
  • 1
  • 10
  • 27

3 Answers3

3
 sets = new ArrayList[5];

Just fills 5 spots with null

You need to explicitly set ArrayList() for each position before doing add() call.

Example:

sets[0] = new ArrayList<Integer>();
sets[0].add(5);
kosa
  • 65,990
  • 13
  • 130
  • 167
1

The line

sets = new ArrayList[5];

allocates the array, but does not place an ArrayList in any element of the array.

You would need

sets[0] = new ArrayList<Integer>();
sets[0].add(1);
Eric J.
  • 147,927
  • 63
  • 340
  • 553
0

It's because your array is initialized with null values.

//it will initialize sets variable
sets = new ArrayList[5];
//but set[0], set[1]... and on are null

You should initialize the array items as well before using them

sets[0] = new ArrayList<Integer>();
sets[0].add(1);

Also, for a better design, you should program oriented to interfaces instead of the class. See What does it mean to "program to an interface"? for more info.

In short, your code should look like

public class A {
    static List<Integer> sets[];
    public static void main(String[] args) {
        sets = new List[5];
        sets[0] = new ArrayList<Integer>();
        sets[0].add(1);
        //extending your code in order to use more than one value of the List array
        sets[1] = new ArrayList<Integer>();
        sets[1].add(20);
        for(List<Integer> list : sets) {
            if (list != null) {
                System.out.println(list.get(0));
            }
        }
    }
}
Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332