Home > Blockchain >  Initializing 2D arrray of Arraylist<Integer> type
Initializing 2D arrray of Arraylist<Integer> type

Time:01-10

I need to use a N by N matrix, where each cell is of type Arraylist. I declared a 2D array like below:

public static int N;
private static ArrayList<Integer>[][] matrix;
public MyConstructor() {
    matrix = new ArrayList[N][N];
}

But, it shows error. How can I initialize that variable "matrix" inside a constructor ?

CodePudding user response:

You cannot initialize a multi-dimensional array in one go in Java. First you have to initialize the outer dimension and then in a loop the inner dimension. This is because the inner dimension is not of a fixed size, you could have arrays of various lengths as inner dimension(s).

Also please don't mix generics and arrays in the way you did in your example, bad confusion is likely to happen.

And don't initialize static variables in the constructor, this should be either done in the declaration or in a static initialization block.

One of the ways to initialize a multi-dimensional array could be:

Integer[][] matrix = new Integer[42][];
java.util.Arrays.setAll(i -> new Integer[123]);

(This examples uses the fixed dimension of 42 and 123 for the both dimensions.)

As the main question seems to be the initialization, I do not cover Generics, mixing with Lists, and static initialization here.

CodePudding user response:

Java will not allow you to create a generic array. Why don't you do it the other way round? Why not implement the matrix as an ArrayList of ArrayLists? I think that would be better.

  • Related