adhdj
adhdj

Reputation: 352

2D static array of dynamic array in Java

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?

Upvotes: 1

Views: 125

Answers (4)

Varun Srivastawa
Varun Srivastawa

Reputation: 72

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]);

Upvotes: 0

NSchorr
NSchorr

Reputation: 925

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);

Upvotes: 0

ryanm
ryanm

Reputation: 451

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

Upvotes: 1

Nikolas
Nikolas

Reputation: 44378

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

Upvotes: 3

Related Questions