1

I have a 2D array as an input of NxM size, where N is known and static, and M actually grows dynamically and will be different for each index of the array[0...N-1].

I was thinking I could initialize my 2D array like so:

ArrayList<Integer>[] array = new ArrayList[n];

but this leaves all sub-arrays initialized to null instead of an ArrayList instance. For example, calling

array[0].add(1);

crashes with a NullPointerException

How do I properly initialize the ArrayLists?

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
adhdj
  • 352
  • 4
  • 17
  • as an aside, consider using `List> myList = new ArrayList<>(n);` rather than `ArrayList[] array = new ArrayList[n];`. – Ousmane D. Mar 24 '18 at 22:31

4 Answers4

3

You have initialized the array itself, not the list at the 1st index (and so on...).

List<Integer>[] array = new ArrayList[n];
array[0] = new ArrayList<>();
array[0].add(1);

Anyway, I recommend you to avoid the array structure and pick List<List<Integer>> instead. Or create tuples class (more info at A Java collection of value pairs? (tuples?)).

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
1

As you'll see at the Oracle documentation

You cannot create arrays of parameterized types.

You could use an ArrayList<ArrayList<T>> or a List<List<T>>.

ryanm
  • 451
  • 2
  • 7
0

Here's how I would do this:

        List<ArrayList<Integer>> complex = new ArrayList <ArrayList<Integer>>();
        ArrayList<Integer> simple = new  ArrayList<Integer>();
        simple.add((Integer)5555);
        complex.add(simple);
NSchorr
  • 875
  • 10
  • 13
0
ArrayList<Integer>[] array = new ArrayList[n];

Instead of doing it. You can do like below:

List<List<Integer>> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
list2.add(2);
list1.add(list2);
ArrayList[] array = list1.toArray(new ArrayList[10]);
System.out.println(array[0]);
MSDN.WhiteKnight
  • 664
  • 7
  • 30