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?

1
  • as an aside, consider using List<ArrayList<Integer>> myList = new ArrayList<>(n); rather than ArrayList<Integer>[] array = new ArrayList[n];. Commented Mar 24, 2018 at 22:31

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

2 Comments

My N is 100K-200K. Would looping through and initializing for each ArrayList be unavoidable?
The initialization is unavoidable regardless the number. Read the recommendation on the second part of my updated answer.
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>>.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.