-3

I have java program like this

public class Distribution {

    private LinkedList<Integer > group[];    

    public Distribution() {
        group[0] = new LinkedList<>();
        group[0].add(1);
        group[0].add(2);
        group[0].add(3);

        group[1] = new LinkedList<>();
        group[1].add(4);
        group[1].add(5);
        group[1].add(6);
    }

    public static void main(String args[])
    {
        Distribution distribution = new Distribution();
    }
}

but the compiler says Exception in thread "main" java.lang.NullPointerException.

dotvav
  • 2,808
  • 15
  • 31
Santosh
  • 1
  • 3

3 Answers3

6

You never initialized your group[].

private LinkedList<Integer> group[] = new LinkedList[2]; //example

You must initialize the array specify the length...

brso05
  • 13,142
  • 2
  • 21
  • 40
2

You have not initialized your array. Use the following code to remove the NullPointerException:

private LinkedList<Integer> group[] = new LinkedList[10];

(where you have to replace 10 by the size you need).

Note that generics and arrays are not really convenient to use together. In particular, the above code gives a compiler warning (because it uses a raw type), and

private LinkedList<Integer> group[] = new LinkedList<Integer>[2];

doesn't compile.

In general, using an array of a generic class is not a good idea. Consider using an ArrayList instead of an array:

public class Distribution {
    private ArrayList<LinkedList<Integer>> group = new ArrayList<>();    

    public Distribution() {
        group.add(new LinkedList<>());
        group.get(0).add(1);
        ...
        group.add(new LinkedList<>());
        group.get(1).add(4);
        ...
    }
    ... 
}
Hoopje
  • 12,677
  • 8
  • 34
  • 50
1

This will solve your problem

private LinkedList<Integer> group[] = new LinkedList[10];

However it will generate a compiler warning.

You cannot/should not create arrays of lists in java

Use Lists of Lists instead of Arrays of Lists

List< List<IntegerNode>> nodeLists = new LinkedList< List< IntegerNode >>();

See Answers to question - Cannot create an array of LinkedLists in Java...?

Community
  • 1
  • 1
CarefreeCrayon
  • 249
  • 2
  • 7